Lesson 82 of 296
EventEmitter
On this page
The task
"Build an EventEmitter class with on, off, emit and once."
What an event emitter is
An event emitter lets parts of a program talk without knowing about each other. One part subscribes to a named event ("when an order is placed, do this"). Another part emits the event ("an order was placed"). Every subscriber's function is called.
This is called the publish-subscribe (pub/sub) pattern, a form of the observer pattern (Part 21). Node.js has a built-in EventEmitter, and browser DOM events work in a similar way.
const emitter = new EventEmitter();
emitter.on("order:placed", (order) => sendEmail(order));
emitter.on("order:placed", (order) => updateStock(order));
emitter.emit("order:placed", { id: 1042 }); both runWhat the interviewer is checking
- Choosing a good data structure: a Map from event name to a list of listeners.
- Removing listeners correctly.
- The tricky part:
once, and removing aoncelistener withoff. - Not breaking when a listener removes itself during
emit.
Questions to ask first
- "Should
onreturn an unsubscribe function?" - "What should
emitreturn?" (Node.js returnstrueif there were listeners.) - "Do errors in one listener need to stop the others?"
The solution
class EventEmitter {
#events = new Map();
on(event, listener) {
if (!this.#events.has(event)) {
this.#events.set(event, []);
}
this.#events.get(event).push(listener);
return () => this.off(event, listener);
}
off(event, listener) {
const listeners = this.#events.get(event);
if (!listeners) return this;
const index = listeners.findIndex(
(l) => l === listener || l.original === listener
);
if (index !== -1) listeners.splice(index, 1);
if (listeners.length === 0) this.#events.delete(event);
return this;
}
once(event, listener) {
const wrapper = (...args) => {
this.off(event, wrapper);
listener.apply(this, args);
};
wrapper.original = listener;
return this.on(event, wrapper);
}
emit(event, ...args) {
const listeners = this.#events.get(event);
if (!listeners) return false;
for (const listener of [...listeners]) {
listener.apply(this, args);
}
return true;
}
listenerCount(event) {
return this.#events.get(event)?.length ?? 0;
}
}The important details
#eventsis a Map from event name to an array of listener functions. Private, so outside code cannot break it.onreturns an unsubscribe function. This is a modern convenience:const stop = emitter.on(...); stop();.oncewraps the listener. The wrapper removes itself first, then calls the real listener. We store the real listener onwrapper.original.offalso matchesoriginal, soemitter.off("x", fn)works even iffnwas added withonce.emitloops over a copy ([...listeners]). If a listener removes itself during the loop (whichoncedoes), changing the real array while looping over it would skip the next listener.spliceremoves one matching listener, like Node.js.
Test it
const e = new EventEmitter();
const log = [];
const a = (x) => log.push("a" + x);
e.on("x", a);
e.once("x", (x) => log.push("once" + x));
e.emit("x", 1); log: ["a1", "once1"]
e.emit("x", 2); log: ["a1", "once1", "a2"] (once listener is gone)
e.off("x", a);
e.emit("x", 3); returns false: no listeners leftFollow-up questions
- "What if a listener throws an error?" Currently it stops the loop. Wrap each call in
try...catchand report errors, or follow Node's rule: an"error"event with no listeners throws. - "What about memory leaks?" Listeners that are never removed keep their closures alive. Node.js warns when more than 10 listeners are added to one event, by default.
- "Async listeners?"
emitdoes not wait for promises. You could add anemitAsyncthat awaits all listeners withPromise.all.
Cost
| Method | Time |
|---|---|
| on | O(1) |
| emit | O(k), k = number of listeners for that event |
| off | O(k) |
Common mistakes
- Looping over the live array in
emitwhileonceremoves items. offfailing foroncelisteners.- Storing listeners in a plain object keyed by event name with no checks (works, but a Map is cleaner).
How to say it in an interview
"I store a Map from event names to arrays of listeners. on pushes a listener and returns an unsubscribe function, emit calls a copy of the listener array with the arguments, so listeners that remove themselves during emit do not cause skipped calls, and off removes the first matching listener. once wraps the listener in a function that removes itself before calling it, and keeps a reference to the original so off can still remove it. This is the publish-subscribe or observer pattern."
Key words
| Word | Meaning |
|---|---|
| Event emitter | An object that lets code subscribe to and emit named events |
| Listener / subscriber | A function called when an event is emitted |
| Emit / publish | Trigger an event |
| Publish-subscribe | A pattern where senders and receivers do not know each other |
| Unsubscribe | Remove a listener |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.