What is the recommended way to implement event-driven communication between components?
class EventBus {
static #instance;
#listeners = new Map();
static getInstance() {
if (!EventBus.#instance) {
EventBus.#instance = new EventBus();
}
return EventBus.#instance;
}
emit(eventName, detail) {
const event = new CustomEvent(eventName, { detail });
document.dispatchEvent(event);
}
on(eventName, callback) {
if (!this.#listeners.has(eventName)) {
this.#listeners.set(eventName, new Set());
}
const handlers = this.#listeners.get(eventName);
handlers.add(callback);
document.addEventListener(eventName, callback);
}
off(eventName, callback) {
const handlers = this.#listeners.get(eventName);
if (handlers) {
handlers.delete(callback);
document.removeEventListener(eventName, callback);
}
}
}
A centralized event bus using custom events is recommended for component communication because:
1. It provides loose coupling:
- Components don't need direct references to each other
- Easier to maintain and modify components independently
- Simpler testing and mocking
2. Implements the publish-subscribe pattern:
- One-to-many communication
- Dynamic subscriber management
- Flexible event handling
3. Centralizes event management:
- Single source of truth for events
- Easier debugging and monitoring
- Consistent event handling patterns
4. Supports scalability:
- Easy to add new subscribers
- Minimal impact when adding new events
- Better code organization