Delegate events from one root listener to matching selectors
A comment feed renders hundreds of “Like”, “Reply”, and “Share” buttons, and new comments stream in while the page is open. Attaching a listener to every button wastes memory and misses buttons added later. The usual fix is event delegation: listen once on a container and work out which button the event came from.
Implement delegate(root, eventType, selector, handler). It adds one listener for eventType on root. When an event of that type bubbles up to root, it calls handler for each element on the path from the event target up to root that matches the CSS selector. It returns a function that removes the listener.
const stop = delegate(root, eventType, selector, handler);
// handler(event, matchedElement), called with this === matchedElement
stop(); // removes the listener
root. Elements added to root after delegate() is called must work too.event.target. If the target is not an element (for example a text node), start at its parent element.selector gets one handler call, from the innermost to the outermost.root: the root itself never matches, and neither do elements outside it, even if they match the selector.handler with the event as the first argument, the matched element as the second, and this set to the matched element. event.target is left unchanged.event.stopPropagation() (or stopImmediatePropagation()), do not call the handler for any outer matches of that event.delegate() call is independent, so several can share one root.// <ul id="feed">
// <li class="comment" data-id="c1">
// <p>Great write-up!</p>
// <button class="like"><span>👍</span> Like</button>
// </li>
// </ul>
const feed = document.getElementById('feed');
const stopLikes = delegate(feed, 'click', '.like', (event, button) => {
const comment = button.closest('.comment');
console.log('liked', comment.dataset.id);
});
// Clicking the 👍 span logs "liked c1": the span is the target,
// and the .like button is the matching ancestor.
// Clicking the <p> logs nothing: no element between it and #feed matches.
stopLikes(); // later clicks log nothing
Tests dispatch bubbling events (such as click and input) on elements they build inside a container.