Last active
October 16, 2018 07:11
-
-
Save gordonbrander/d7b3dc4a0c15f950bcf7e6a4b7000ac7 to your computer and use it in GitHub Desktop.
addEventDelegate() - easy event delegation
This file contains 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
// Copyright 2018 Gordon Brander | |
// Released under MIT License https://opensource.org/licenses/MIT | |
const closest = (el, selector) => | |
el.closest ? el.closest(selector) : null; | |
/** | |
* Delegate event handling to a parent element. | |
* @arg {Element} el - the parent element that we will be delegating handling to. | |
* @arg {string} selector - CSS selector of elements that should receive events. | |
* @arg {string} event - name of event | |
* @arg {function} callback - event callback. Takes 2 arguments event, and matched target. | |
* @arg {Object} options - event options | |
* @return {function} to remove event handler | |
*/ | |
export const addEventDelegate = (el, selector, event, callback, options) => { | |
const onEvent = event => { | |
const target = closest(event.target, selector); | |
if (target) { | |
callback(event, target); | |
} | |
} | |
el.addEventListener(event, onEvent, options); | |
return () => el.removeEventListener(event, onEvent, options); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment