QuestionsJavaScript

Implement an EventEmitter (pub/sub)

Implement from scratchMediumJavaScript

Build a small event emitter supporting on, off, emit, and once.

What it tests

Closures, data-structure choice, and the observer pattern that underpins most UI event code.

Approach & answer

Keep a Map from event name to a Set of listener functions. on adds a listener (returning an unsubscribe function is a nice ergonomic touch that mirrors addEventListener and RxJS). off removes one. emit iterates the set and calls each listener with the payload — iterate over a copy so a listener that unsubscribes mid-emit doesn't corrupt the iteration. once wraps the listener in a self-removing wrapper so it fires at most one time. A Map of Sets gives O(1) add/remove and naturally de-dupes identical listeners. This is the observer pattern: it decouples producers from consumers, which is exactly how DOM events, Node's EventEmitter, Redux subscriptions, and custom hooks over external stores work.

Use this technique when

Decoupling modules, bridging non-React stores into hooks, and cross-component signaling without prop drilling.

References

js