📢 Custom EventEmitter Implementation
Category: js / utils
Difficulty: hard
Interview Importance: 🔴 Critical — EventEmitter is a classic interview question that tests understanding of the Observer pattern, closures, memory management, and JavaScript fundamentals. 1️⃣ What is an EventEmitter? An EventEmitter (or Event Bus) is a pattern that allows objects to subscribe to and publish events. It's the foundation of event-driven programming in JavaScript. [code example] Real-World Examples Event System EventEmitter class DOM Custom hooks, Context Vue Subjects and Observables | 2️⃣ Why Implement EventEmitter? Decouples components — Publishers don't know about subscribers Flexible communication — Many-to-many relationships Interview staple — Tests multiple JS concepts Real-world usage — Foundation of reactive programming What This Tests Closures & Scoping — Managing listener references Memory Management — Proper cleanup to prevent leaks Data Structures — Efficient storage with Map and Set Design Patterns — Observer/Pub-Sub pattern 3️⃣ Implementation Basic Implementation ```javascript class EventEmitter { constructor() { this.events = new Map(); } // Subscribe to an event on(event, listener) { if (!this.events.has(event)) { this.events.set(event, new Set()); } this.events.get(event).add(listener); return this; // Enable chaining } // Unsubscribe from an event off(event, listener) { if (this.events.has(event)) { this.events.get(event).delete(listener); // Clean up empty event sets if (this.events.get(event).size === 0) { this.events.delete(event); } } return this; } // Emit an event to all listeners emit(event, ...args) { if (this.events.has(event)) { for (const listener of this.events.get(event)) { listener(...args); } } return this; } // Subscribe for a single event only once(event, listener) { const onceWrapper = (...args) => { this.off(event, onceWrapper); // Remove before calling listener(...args); }; this.on(event, onceWrapper); return this; }...