event delegation
2022年5月1日小于 1 分钟
event delegation
Question
Can you create a function which works like jQuery.on(), that attaches event listeners to selected elements.
In jQuery, selector is used to target the elements, in this problem, it is changed to a predicate function.
onClick(
// root element
document.body,
// predicate
(el) => el.tagName.toLowerCase() === 'div',
function(e) {
console.log(this);
// this logs all the `div` element
}
)
event.stopPropagation() and event.stopImmediatePropagation() should also be supported.
you should only attach one real event listener to the root element.
Code
/**
* @param {HTMLElement} root
* @param {(el: HTMLElement) => boolean} predicate
* @param {(e: Event) => void} handler
*/
function onClick(root, predicate, handler) {
// your code here
}