Custom Event Emitter
What you'll build
An EventEmitter class with on (subscribe), off (unsubscribe), emit (publish), and once (subscribe for a single emission).
Goals
- Store listeners in a Map keyed by event name
- Implement on/off/emit/once methods
- Support multiple listeners per event
- Understand the pub/sub decoupling pattern
Prerequisites
- Objects and Maps
- Array methods (push, filter)
- Functions as first-class values
Steps
- 1
Set up the listener store
Create an EventEmitter class with a Map of event names to listener arrays. The Map is the core data structure for pub/sub.
Codeclass EventEmitter { constructor() { this.listeners = new Map(); } }Expected result
An emitter with an empty listeners Map.
- 2
Implement on and emit
on(event, fn) adds fn to the listener array for that event (creating the array if needed). emit(event, ...args) calls every listener with the args.
Codeon(event, fn) { if (!this.listeners.has(event)) this.listeners.set(event, []); this.listeners.get(event).push(fn); return this; } emit(event, ...args) { const fns = this.listeners.get(event) || []; fns.forEach(fn => fn(...args)); return this; }Expected result
on('greet', console.log); emit('greet', 'hi') logs 'hi'.
- 3
Implement off
off(event, fn) removes a specific listener. Use filter to keep all listeners except the given function reference.
Hint
Compare with === since functions are reference types — the caller must pass the exact same function.
- 4
Implement once
once(event, fn) subscribes fn but auto-removes it after the first emission. Implement by wrapping fn in a wrapper that calls fn then calls off.
Hint
Define a wrapper inside once, subscribe the wrapper, and have the wrapper unsubscribe itself.
- 5
Test the emitter
Subscribe multiple listeners, emit, unsubscribe one, emit again, and test once. Verify the pub/sub decoupling: emitters and listeners don't need to know about each other.
Codeconst ee = new EventEmitter(); const handler = (msg) => console.log('A:', msg); ee.on('msg', handler); ee.on('msg', (msg) => console.log('B:', msg)); ee.once('msg', (msg) => console.log('Once:', msg)); ee.emit('msg', 'hello'); // A, B, Once ee.emit('msg', 'world'); // A, B (once gone) ee.off('msg', handler); ee.emit('msg', 'test'); // B onlyExpected result
First emit prints A, B, Once; second prints A, B; third prints B only.
Try it yourself
class EventEmitter {
constructor() { this.listeners = new Map(); }
// TODO: on, off, emit, once
}class EventEmitter {
constructor() { this.l = new Map(); }
on(e, f) { if (!this.l.has(e)) this.l.set(e, []); this.l.get(e).push(f); return this; }
off(e, f) { const a = this.l.get(e); if (a) this.l.set(e, a.filter(x => x !== f)); return this; }
emit(e, ...a) { (this.l.get(e) || []).forEach(f => f(...a)); return this; }
once(e, f) { const w = (...a) => { f(...a); this.off(e, w); }; this.on(e, w); return this; }
}What you learned
You built the pub/sub pattern that powers Node's EventEmitter, the DOM, React state libraries, and most message-bus systems — decoupling producers from consumers.
Related Resources
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.