Build an Event Emitter
The Event Emitter pattern is everywhere in software:
- Node.js
EventEmitterβ HTTP servers, file streams - React β synthetic event system
- DOM β
addEventListener - Vue/Angular β component communication
Understanding it proves you understand observer pattern, pub/sub, and callback-based async.
The Spec
Build an EventEmitter class:
on(event, listener)β subscribe to an eventoff(event, listener)β unsubscribeemit(event, ...args)β fire all listeners for an eventonce(event, listener)β subscribe for only the NEXT occurrencelistenerCount(event)β how many listeners for this event
Why It Matters
Most async patterns are built on this:
const server = http.createServer();
server.on("request", handleRequest); // built-in EventEmitter
server.on("close", cleanup);
server.emit("custom", { data: 123 });
Building your own forces you to think about:
- Data structures for listeners (Map of arrays)
- Cleanup (memory leaks from uncleaned listeners)
- Error handling
β‘ 50 XP
solution.jsRuns in your browser
Loading editorβ¦
Tests4 to pass
on + emit fires listener
off removes listener
once fires only once
emit passes args
Run your code to check these.