IK
Interview Knowledge Book
Topics
Practice
Examples
Playground
RU
browser
Delegated DOM event handling
Use one parent listener to handle child button actions and dispatch a small custom event.
index.js
const toolbar = { listeners: {}, addEventListener(type, listener) { this.listeners[type] = listener; }, dispatchEvent(event) { this.listeners[event.type]?.(event); }, }; toolbar.addEventListener('click', (event) => { const action = event.target?.dataset?.action; if (!action) return; console.log('clicked', action); toolbar.dispatchEvent({ type: 'toolbar-action', detail: action }); }); toolbar.addEventListener('toolbar-action', (event) => console.log('custom detail', event.detail)); toolbar.dispatchEvent({ type: 'click', target: { dataset: { action: 'save' } } });
Run
Stop
Reset