An Event Emitter (or Pub-Sub) is one of the most practical design patterns in JavaScript — it powers Node.js's EventEmitter, browser events, and virtually every state management library. This article implements on, off, emit, and once from scratch.
Prerequisites: JS Foundations #3 — Closures
1. Basic Event Emitter — on, emit
Loading editor...
2. once() — Listen for Exactly One Event
Loading editor...
3. removeAllListeners and listenerCount
Loading editor...
4. Wildcard / Catch-All Events — "*"
Node.js EventEmitter doesn't support wildcards, but you can add it:
Loading editor...
5. Max Listeners Warning (Node.js Convention)
Node warns when more than 10 listeners are attached to one event:
Loading editor...
Key Takeaways
on(event, cb): register a listener — returnsthisfor chaining.emit(event, ...args): call all listeners for that event synchronously.off(event, cb): remove a specific listener by function reference.once(event, cb): wrap the callback, auto-remove after first emit.- Wildcard
"*": emit to both specific and catch-all listeners. - Node.js
EventEmitteris synchronous — listeners run in the order they were added.
Next: Patterns #2 — Observer Pattern & Reactive Primitives — build a basic Observable with subscribe/unsubscribe/notify.
