Skip to the content

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 run

What 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 a once listener with off.
  • Not breaking when a listener removes itself during emit.

Questions to ask first

  • "Should on return an unsubscribe function?"
  • "What should emit return?" (Node.js returns true if 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

  • #events is a Map from event name to an array of listener functions. Private, so outside code cannot break it.
  • on returns an unsubscribe function. This is a modern convenience: const stop = emitter.on(...); stop();.
  • once wraps the listener. The wrapper removes itself first, then calls the real listener. We store the real listener on wrapper.original.
  • off also matches original, so emitter.off("x", fn) works even if fn was added with once.
  • emit loops over a copy ([...listeners]). If a listener removes itself during the loop (which once does), changing the real array while looping over it would skip the next listener.
  • splice removes 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 left

Follow-up questions

  • "What if a listener throws an error?" Currently it stops the loop. Wrap each call in try...catch and 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?" emit does not wait for promises. You could add an emitAsync that awaits all listeners with Promise.all.

Cost

MethodTime
onO(1)
emitO(k), k = number of listeners for that event
offO(k)

Common mistakes

  • Looping over the live array in emit while once removes items.
  • off failing for once listeners.
  • 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

WordMeaning
Event emitterAn object that lets code subscribe to and emit named events
Listener / subscriberA function called when an event is emitted
Emit / publishTrigger an event
Publish-subscribeA pattern where senders and receivers do not know each other
UnsubscribeRemove a listener

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.