Last active
December 31, 2018 05:59
-
-
Save iwfan/4c3ccbefbec4423f2d82fac796624d14 to your computer and use it in GitHub Desktop.
[Event Delegation] 事件代理 #event
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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