Problem
UI components, websocket clients and analytics layers all rely on events, and building an EventEmitter class in JavaScript with subscribe, emit and unsubscribe is a frequent frontend interview task.
Implement a class EventEmitter with two methods:
subscribe(eventName, callback)registerscallbackforeventNameand returns a subscription handle object with aremove()method.emit(eventName, ...args)calls every callback currently subscribed toeventName, passing along allargs.
Requirements
- Multiple callbacks can subscribe to the same event;
emitcalls each of them, in the order they subscribed. - All extra arguments passed to
emitare forwarded to each callback unchanged. - Calling
remove()on a handle stops only that subscription; other subscribers to the same event keep receiving events. - Emitting an event that has no subscribers (or whose subscribers were all removed) does nothing and does not throw.
- Separate
EventEmitterinstances do not share subscriptions.
Example
const emitter = new EventEmitter();
const a = emitter.subscribe("save", (id, ok) => console.log("A", id, ok));
const b = emitter.subscribe("save", (id) => console.log("B", id));
emitter.emit("save", 7, true);
// A 7 true
// B 7
a.remove();
emitter.emit("save", 8, false);
// B 8
emitter.emit("unknown", 1); // (nothing logged)
Follow-ups
- What should happen if the same callback is subscribed twice?
- What if a callback removes itself or another subscription while
emitis running? - How would you add a
once(eventName, callback)method?