Created
September 21, 2017 05:04
-
-
Save webbower/683b91a4a6146ff6aa40c52d539daaac to your computer and use it in GitHub Desktop.
Event delegation wrapper/HOF
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 delegate(selector, handler) { | |
return (ev) => { | |
const tgt = ev.target; | |
// Check if the event target matches the selector or if it is a descendant | |
// of the selector | |
if (tgt.matches(selector) || tgt.matches(`${selector} ${tgt.nodeName.toLowerCase()}`)) { | |
// Since `ev.target` is the deepest element that triggered the event, it | |
// won't always match the selector for the delegated event, so we add a | |
// custom key to the event object for the delegate event target. | |
handler(Object.assign(ev, { delegateTarget: closest(tgt, selector) })); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment