Skip to content

Commit 324b8fe

Browse files
committed
test event delegation
1 parent b3b70cb commit 324b8fe

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/utils/dom.ts

+33
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,35 @@ const $_className = 'className';
8080

8181
let unstableWrapperId: number = 0;
8282
let ROOT: Component<any> | null = null;
83+
let delegatedEvents: Record<string, WeakMap<HTMLElement, (e: Event) => void>> = {
84+
click: new WeakMap(),
85+
};
86+
87+
function handleDelegatedEvent(e: Event) {
88+
let target = e.target as HTMLElement;
89+
let maxDepth = 3;
90+
while (target && target !== document.body && maxDepth > 0) {
91+
maxDepth--;
92+
if (delegatedEvents.click.has(target)) {
93+
break;
94+
}
95+
target = target.parentElement!;
96+
}
97+
const fn = delegatedEvents.click.get(target);
98+
if (fn) {
99+
fn(e);
100+
}
101+
}
102+
103+
if (!IN_SSR_ENV) {
104+
Object.keys(delegatedEvents).forEach((name) => {
105+
document.addEventListener(name, handleDelegatedEvent);
106+
});
107+
}
108+
109+
export function $_delegateEvent(element: HTMLElement, name: string, fn: (e: Event) => void) {
110+
delegatedEvents[name].set(element, fn);
111+
}
83112

84113
export function $_componentHelper(params: any, hash: any) {
85114
const componentFn = params.shift();
@@ -349,6 +378,10 @@ function $ev(
349378
}
350379
}
351380
} else {
381+
if (eventName === 'click') {
382+
$_delegateEvent(element, eventName, fn as EventListener);
383+
return;
384+
}
352385
// event case (on modifier)
353386
if (RUN_EVENT_DESTRUCTORS_FOR_SCOPED_NODES) {
354387
destructors.push(

0 commit comments

Comments
 (0)