diff --git a/src/utils/dom.ts b/src/utils/dom.ts index 2a5ff4b..7ff500f 100644 --- a/src/utils/dom.ts +++ b/src/utils/dom.ts @@ -27,7 +27,7 @@ import { destroy, registerDestructor, } from './glimmer/destroyable'; -import { api } from '@/utils/dom-api'; +import { api, getDocument } from '@/utils/dom-api'; import { isFn, isPrimitive, @@ -86,25 +86,25 @@ let delegatedEvents: Record void>> = function handleDelegatedEvent(e: Event) { let target = e.target as HTMLElement; - let maxDepth = 3; - while (target && target !== document.body && maxDepth > 0) { - maxDepth--; + const body = getDocument().body; + while (target && target !== body) { if (delegatedEvents.click.has(target)) { break; } target = target.parentElement!; } + if (!target.isConnected) { + return; + } const fn = delegatedEvents.click.get(target); if (fn) { fn(e); } } -if (!IN_SSR_ENV) { - Object.keys(delegatedEvents).forEach((name) => { - document.addEventListener(name, handleDelegatedEvent); - }); -} +Object.keys(delegatedEvents).forEach((name) => { + api.addEventListener(getDocument(), name, handleDelegatedEvent); +}); export function $_delegateEvent(element: HTMLElement, name: string, fn: (e: Event) => void) { delegatedEvents[name].set(element, fn);