Event delegation in JavaScript
One listener on the container handles every child, now and later.
function wire(container, onPick) {
const controller = new AbortController();
container.addEventListener("click", (event) => {
const row = event.target.closest("[data-idx]");
if (!row || !container.contains(row)) return;
event.preventDefault();
onPick(Number(row.dataset.idx));
}, { signal: controller.signal });
container.addEventListener("keydown", (event) => {
if (event.key === "Escape") controller.abort();
}, { once: true });
return () => controller.abort();
}
How it works
event.target.closestfinds the row that was clicked.- Delegation survives nodes added after the listener.
{ once: true }and{ signal }control the listener's life.
Keywords and builtins used here
Numberconstfunctionifreturn
The run, in numbers
- Lines
- 16
- Characters to type
- 468
- Tokens
- 128
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 77 seconds.
Step 2 of 3 in Events, step 5 of 13 in The browser.