Event emitters are everywhere: Node's EventEmitter, the DOM's addEventListener, every state library you've used. Writing one yourself takes about fifty lines, and it's a great exercise because there's one subtle bug almost every first attempt has. Let's build it, test it with Node's built-in test runner, and fix that bug on purpose.
The API
const e = new Emitter();
const stop = e.on('message', (text) => console.log(text));
e.once('ready', () => console.log('ready, only once'));
e.emit('message', 'hello'); // logs "hello", returns true
stop(); // unsubscribe
e.emit('message', 'again'); // nothing happens, returns false
Four methods: on, once, off, emit. on and once return an unsubscribe function, which is much nicer than holding on to the handler just to call off later.
The implementation
class Emitter {
constructor() {
this.listeners = new Map(); // event -> array of { fn, once }
}
on(event, fn) {
if (typeof fn !== 'function') throw new TypeError('listener must be a function');
if (!this.listeners.has(event)) this.listeners.set(event, []);
this.listeners.get(event).push({ fn, once: false });
return () => this.off(event, fn);
}
once(event, fn) {
this.on(event, fn);
const list = this.listeners.get(event);
list[list.length - 1].once = true;
return () => this.off(event, fn);
}
off(event, fn) {
const list = this.listeners.get(event);
if (!list) return false;
const i = list.findIndex((l) => l.fn === fn);
if (i === -1) return false;
list.splice(i, 1);
if (list.length === 0) this.listeners.delete(event);
return true;
}
emit(event, ...args) {
const list = this.listeners.get(event);
if (!list) return false;
for (const l of [...list]) { // <- the important copy
if (l.once) this.off(event, l.fn);
l.fn.apply(this, args);
}
return true;
}
listenerCount(event) {
return (this.listeners.get(event) || []).length;
}
}
A few choices worth explaining:
-
A
Map, not a plain object. Event names likeconstructoror__proto__won't collide with anything. -
Listeners stored as
{ fn, once }. This letsoffwork the same for normal and one-time listeners, because you remove by the original function. -
Empty lists get deleted, so
emitcan cheaply returnfalsewhen nobody is listening, the same contract as Node.
The bug: mutating the array while you loop over it
The naive emit looks like this:
for (const l of list) { ... }
Now imagine listener A removes listener B while the event is firing. splice shifts every later element one slot left, the loop index moves forward, and the listener right after the removed one gets skipped. once listeners trigger the same bug, because they remove themselves mid-loop.
Copying the array first ([...list]) freezes the set of listeners for this emit. Everyone who was subscribed when emit started gets called exactly once, which is also how Node's own EventEmitter behaves. Changes take effect on the next emit.
Tests with node:test
No dependencies needed on Node 18+:
const test = require('node:test');
const assert = require('node:assert');
const { Emitter } = require('./emitter');
test('once fires a single time', () => {
const e = new Emitter();
let n = 0;
e.once('tick', () => n++);
e.emit('tick'); e.emit('tick');
assert.strictEqual(n, 1);
assert.strictEqual(e.listenerCount('tick'), 0);
});
test('removing a listener during emit does not skip others', () => {
const e = new Emitter();
const calls = [];
const a = () => { calls.push('a'); e.off('ev', b); };
const b = () => calls.push('b');
e.on('ev', a); e.on('ev', b);
e.emit('ev');
assert.deepStrictEqual(calls, ['a', 'b']); // b still runs this time
e.emit('ev');
assert.deepStrictEqual(calls, ['a', 'b', 'a']); // and is gone next time
});
Run it with node --test. My full suite (six tests, including argument passing, unsubscribe, and rejecting non-function listeners) passes on Node 20.
Where to go from here
- Add a wildcard
'*'event that receives every emit. - Catch errors per listener so one throwing handler doesn't stop the rest.
- Add TypeScript generics so
emit('message', 42)fails to compile whenmessageexpects a string.
Small, boring, well-tested utilities are the ones you end up trusting the most. What would you add?
Top comments (0)