Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
addEventDelegate() - easy event delegation
// 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
You can’t perform that action at this time.