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.
Question Bank
Medium
JavaScript
4 questions
quiz
js-event-delegation
js-dom
design-patterns
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.// HTML
// <div id="parent">
// <button class="child">Button 1</button>
// <button class="child">Button 2</button>
// </div>
// attach the delegated listenerImplement 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.class EventBus {
constructor() {
this.events = {};
}
// on, emit, off
}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.class EventDispatcher {
// implement listeners, addEventListener, removeEventListener, dispatchEvent
}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.// dispatch a CustomEvent on document
// listen for it and log the id