Skip to content

Instantly share code, notes, and snippets.

@webbower
Created September 21, 2017 05:04
Show Gist options
  • Save webbower/683b91a4a6146ff6aa40c52d539daaac to your computer and use it in GitHub Desktop.
Save webbower/683b91a4a6146ff6aa40c52d539daaac to your computer and use it in GitHub Desktop.
Event delegation wrapper/HOF
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