Skip to content

Instantly share code, notes, and snippets.

@iwfan
Last active December 31, 2018 05:59
Show Gist options
  • Save iwfan/4c3ccbefbec4423f2d82fac796624d14 to your computer and use it in GitHub Desktop.
Save iwfan/4c3ccbefbec4423f2d82fac796624d14 to your computer and use it in GitHub Desktop.
[Event Delegation] 事件代理 #event
function delegationEvent(
type: string,
target: HTMLElement,
selector: string,
callback: (
this: HTMLElement | null,
event: Event,
element: HTMLElement | null
) => any
) {
target.addEventListener(type, function(this: HTMLElement, event: Event) {
let ele: HTMLElement | null = event.target as HTMLElement | null;
while (ele && !ele.matches(selector)) {
if (ele === this) {
ele = null;
break;
}
ele = ele.parentElement;
}
callback.call(ele, event, ele);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment