← Back to Node.js, page 10

nodejs-0193 · Medium mid

Implement a small EventEmitter from scratch: on, once, off, emit, and the special 'error' event. What details do people forget?

An emitter stores arrays of listeners by event name. emit calls each listener synchronously with the arguments and with this set to the emitter, and returns whether any listener existed. once wraps the listener so it removes itself before running. Details that people forget: copy the array before calling (so removal during emit is safe), let off find a once wrapper by the original function, and throw when 'error' is emitted with no listener.

Full answer

Data model: a Map from event name to an array of listener entries. An entry holds the function to call and the original function (they differ for once).

Methods

  • on(event, fn): push the listener and return this, so calls can be chained.
  • prependListener(event, fn): same, but at the start of the array.
  • once(event, fn): register a wrapper that first removes itself, then calls fn. Store fn as the original so off(event, fn) works before the event fires.
  • off(event, fn): remove the first entry whose function or original equals fn. Delete the key when the array is empty to avoid leaks.
  • emit(event, ...args): take a copy of the listeners, call each with this as the emitter, and return true when at least one listener existed. Calls are synchronous and in registration order.
  • listenerCount(event).

Details

  • Copy before looping. A once wrapper (or any listener) that removes itself during emit would shift the array and skip the next listener.
  • The special event 'error': if nobody listens, emit('error', err) must throw the error (or wrap it), because swallowing it hides failures.
  • Exceptions inside a listener stop the loop in the built-in emitter. Document the behaviour you choose.
  • Memory: listeners that are never removed are a classic leak. Node warns when more than 10 listeners are added to one event (setMaxListeners).
  • Listeners are synchronous. If you need async handling, use events.once or the async iterator (events.on).
javascript
class Emitter {
  #events = new Map();

  #add(event, entry, prepend) {
    const list = this.#events.get(event) ?? [];
    prepend ? list.unshift(entry) : list.push(entry);
    this.#events.set(event, list);
    return this;
  }
  on(event, fn) { return this.#add(event, { fn, original: fn }, false); }
  prependListener(event, fn) { return this.#add(event, { fn, original: fn }, true); }
  once(event, fn) {
    const wrapper = (...args) => { this.off(event, fn); return fn.apply(this, args); };
    return this.#add(event, { fn: wrapper, original: fn }, false);
  }
  off(event, fn) {
    const list = this.#events.get(event);
    if (!list) return this;
    const index = list.findIndex((entry) => entry.original === fn || entry.fn === fn);
    if (index !== -1) list.splice(index, 1);
    if (list.length === 0) this.#events.delete(event);
    return this;
  }
  emit(event, ...args) {
    const list = this.#events.get(event);
    if (!list || list.length === 0) {
      if (event === 'error') throw args[0] instanceof Error ? args[0] : new Error('Unhandled error: ' + args[0]);
      return false;
    }
    for (const entry of [...list]) entry.fn.apply(this, args);       // a copy, so removal while emitting is safe
    return true;
  }
  listenerCount(event) { return this.#events.get(event)?.length ?? 0; }
}

const bus = new Emitter();
const seen = [];
const first = () => seen.push('first');
bus.on('go', first).once('go', function (x) { seen.push('once:' + x + ':' + (this === bus)); }).on('go', (x) => seen.push('last:' + x));
bus.prependListener('go', () => seen.push('prepended'));

console.log('emit returns      :', bus.emit('go', 1), bus.emit('nobody'));
bus.emit('go', 2);
console.log('calls             :', seen.join(' | '));
console.log('listeners now     :', bus.listenerCount('go'));

const removed = new Emitter();
const never = () => seen.push('never');
removed.once('x', never).off('x', never);
console.log('off before once   :', removed.emit('x'), 'listeners =', removed.listenerCount('x'));

const selfRemoving = new Emitter(); const order = [];
const a = () => { order.push('a'); selfRemoving.off('e', a); };
selfRemoving.on('e', a).on('e', () => order.push('b'));
selfRemoving.emit('e'); selfRemoving.emit('e');
console.log('self removal safe :', order.join(','));

try { new Emitter().emit('error', new Error('boom')); } catch (err) { console.log("'error' with no listener throws:", err.message); }

The same checks can be run against require('node:events') to compare the behaviour of the built-in class. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): emit returns : true false calls : prepended | first | once:1:true | last:1 | prepended | first | last:2 listeners now : 3 off before once : false listeners = 0 self removal safe : a,b,b 'error' with no listener throws: boom

Key points

  • Store listeners in arrays by event name.
  • emit is synchronous, in registration order, with this set to the emitter.
  • once removes itself before it runs, and off must also find it by the original function.
  • Copy the array before calling listeners.
  • Emitting 'error' with no listener should throw.

Common mistakes

  • Looping over the live array while listeners remove themselves.
  • Making off unable to remove a once listener.
  • Ignoring the special 'error' event.
  • Forgetting to remove listeners, which leaks memory.
  • Expecting emit to wait for async listeners.

Follow-ups

  • How does events.once(emitter, 'x') work?
  • What does setMaxListeners warn about?
  • How would you add async listeners in order (emitSerial)?

Tips

  • Describe the Map of arrays.
  • Call out the copy-before-loop detail.
  • Mention the 'error' event.