Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Build an event emitter in JavaScript

104 an event emitter with on, off, once and emit

fair

Write an emitter class with a private handler table. on should return an unsubscribe function, once should remove itself after firing, emit should report how many handlers ran, and off should say whether it removed anything. Store handlers in a Set and work out what that does to a duplicate subscription.

Stuck? Three hints, smallest first
  1. 1. A Map from event name to a Set of handlers. The Map keeps event names apart; the Set keeps the handler list unique.
  2. 2. once needs no new bookkeeping: register a wrapper that unsubscribes itself and then calls through.
  3. 3. Iterate a copy of the Set inside emit. Then a handler that subscribes another handler cannot join the emit it is already inside.

The answer

class Emitter {
  #handlers = new Map();

  on(event, handler) {
    if (!this.#handlers.has(event)) this.#handlers.set(event, new Set());
    this.#handlers.get(event).add(handler);
    return () => this.off(event, handler);          // an unsubscribe, not a boolean
  }

  once(event, handler) {
    const wrapped = (...args) => {
      this.off(event, wrapped);
      handler(...args);
    };
    return this.on(event, wrapped);
  }

  off(event, handler) {
    const set = this.#handlers.get(event);
    if (!set) return false;
    const removed = set.delete(handler);
    if (set.size === 0) this.#handlers.delete(event);
    return removed;
  }

  emit(event, ...args) {
    const set = this.#handlers.get(event);
    if (!set) return 0;
    let called = 0;
    for (const handler of [...set]) {               // a copy, so growth waits its turn
      handler(...args);
      called++;
    }
    return called;
  }

  count(event) {
    return this.#handlers.get(event)?.size ?? 0;
  }
}

const log = [];
const bus = new Emitter();
const offReceipt = bus.on('paid', (ref, amount) => log.push(`receipt ${ref} ${amount}`));
bus.on('paid', (ref) => log.push(`ledger ${ref}`));
const firstEmit = bus.emit('paid', 'ORD-771', 4500);

offReceipt();
const secondEmit = bus.emit('paid', 'ORD-772', 900);
const noHandlers = bus.emit('refunded', 'ORD-773');

bus.once('shipped', (ref) => log.push(`sms ${ref}`));
const onceFirst = bus.emit('shipped', 'ORD-771');
const onceSecond = bus.emit('shipped', 'ORD-772');
const shippedLeft = bus.count('shipped');

const audit = (ref) => log.push(`audit ${ref}`);
bus.on('closed', audit);
bus.on('closed', audit);
const closedCount = bus.count('closed');
const closedCalls = bus.emit('closed', 'ORD-771');

const removedUnknown = bus.off('paid', () => {});
const paidLeft = bus.count('paid');

let lateCalls = 0;
const grower = new Emitter();
grower.on('tick', () => grower.on('tick', () => { lateCalls++; }));
const firstTick = grower.emit('tick');
const secondTick = grower.emit('tick');

const shape = [Object.keys(bus).length, JSON.stringify(bus)];

console.log('log     :', log);
console.log('emits   :', firstEmit, secondEmit, noHandlers);
console.log('once    :', onceFirst, onceSecond, '| left:', shippedLeft);
console.log('growth  :', firstTick, secondTick, '| late calls:', lateCalls);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('every handler for the event runs, in the order it was added', log.slice(0, 2), ['receipt ORD-771 4500', 'ledger ORD-771']);
test('emit reports how many ran, and an event nobody listens to is 0', [firstEmit, secondEmit, noHandlers], [2, 1, 0]);
test('the function on() returned took off exactly one handler', log[2], 'ledger ORD-772');
test('once fires and removes itself, leaving nothing behind', [onceFirst, onceSecond, shippedLeft], [1, 0, 0]);
test('a Set means the same function subscribed twice is one subscription', [closedCount, closedCalls], [1, 1]);
test('off with a handler that was never on returns false and disturbs nothing', [removedUnknown, paidLeft], [false, 1]);
test('a handler added during an emit waits for the next one', [firstTick, secondTick, lateCalls], [1, 2, 1]);
test('the handler table is a private field, so the instance projects to nothing', shape, [0, '{}']);

Returning an unsubscribe function from on rather than expecting the caller to keep the handler and pass it back to off is the single best decision in this class. The caller almost never has a name for an inline arrow, so off with the same arrow written out again silently removes nothing — two arrows with identical bodies are different functions. A closure over the exact handler cannot get that wrong.

The Set earns its place and costs something. It makes a duplicate subscription free of charge, which is the behaviour you want when a component might mount twice, and it makes removal cheap. It also means you genuinely cannot register the same function twice on purpose, which occasionally surprises people. once falling out as a four-line wrapper over on and off, with no extra state anywhere, is the payoff for having those two right.

Two details that matter in production. Iterating a copy inside emit makes the handler list for this emit fixed at the start, so a handler that subscribes another handler does not get it called in the same round, and a handler that unsubscribes mid-emit does not disturb the walk. And emit here calls handlers synchronously with no try/catch, so one throwing handler stops the rest — fine for a small internal bus, wrong for anything where subscribers are strangers. Wrap each call, collect the errors, and emit them on an 'error' event.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.