Question Bank
Event Delegation and Event Bus Quiz
Difficulty: Medium
Practice DOM event delegation, build a minimal pub/sub event bus, and roll your own dispatcher so cross-component communication stays decoupled.
Event Delegation and Event Bus Quiz
Practice DOM event delegation, build a minimal pub/sub event bus, and roll your own dispatcher so cross-component communication stays decoupled.
569 views
10
Attach a single click listener on #parent that uses event delegation to log the text of any clicked .child button. Don't add per-button listeners.
Examples
Example 1:
Input: user clicks button with text 'Button 2'
Output: 'Button clicked: Button 2'
Explanation: The click bubbles up to `#parent`; the listener checks `e.target.matches('button.child')` to filter.Implement an EventBus class with on(name, listener), emit(name, data), and off(name, listener) for cross-component pub/sub.
Examples
Example 1:
Input: bus.on('saved', fn); bus.emit('saved', { id: 1 });
Output: fn is called with { id: 1 }
Explanation: `on` registers a callback under the event name; `emit` invokes every registered callback with the payload.Build an EventDispatcher with addEventListener, removeEventListener, and dispatchEvent. Show it firing a sayHello event.
Examples
Example 1:
Input: dispatcher.addEventListener('sayHello', name => console.log(`Hello, ${name}!`)); dispatcher.dispatchEvent('sayHello', 'Alice')
Output: 'Hello, Alice!'
Explanation: The dispatcher invokes every listener registered under 'sayHello' with the dispatched argument.Compare native DOM CustomEvent against a JS-side event bus. Show how to fire a typed CustomEvent('userSaved', { detail: ... }) and listen for it on document.
Examples
Example 1:
Input: document.addEventListener('userSaved', e => console.log(e.detail.id)); document.dispatchEvent(new CustomEvent('userSaved', { detail: { id: 42 } }))
Output: 42
Explanation: CustomEvent rides the DOM's built-in dispatch system; you get bubbling, capturing, and `removeEventListener` for free.