Problem, as an interviewer would state it:
"Implement delegate(container, selector, eventType, handler) — attach ONE real listener to container, and have it correctly fire handler only when the actual clicked element matches selector, INCLUDING elements added to the DOM later."
Examples:
delegate(list, "li", "click", (event, target) => console.log(target.textContent));
// works for every <li>, even ones added to the list AFTER this call
Clarifying questions expected:
- Should this work correctly for elements added to the DOM AFTER the delegate() call — the whole real reason to use delegation over binding individual listeners?
- What if the real click target is a nested element INSIDE a matching one (e.g., an icon inside an
<li>)? - Does the handler need access to the actual matched element, not just the raw event?
Code / implementation expected: Yes — real, direct proof against a real DOM: a click on an element added AFTER the listener attached still correctly fires the handler, and a click on a non-matching element does not.