Custom Event Emitter / PubSub
mediumDOM & UtilitiesHigh freq+250 XPFrontend AlgoArena
The publish/subscribe pattern underpins Node's EventEmitter, DOM events, Redux-style stores, and virtually every message bus you've ever used. Decoupling emitters from consumers is what lets independent modules communicate without hard references.
Implement an EventEmitter class with .on(event, listener), .emit(event, ...args), and .off(event, listener). Multiple listeners for the same event must all fire, in registration order, when the event is emitted.
Arguments
.on(event, listener)(event: string, listener: Function) => void- Register a listener to be invoked whenever
eventis emitted. .emit(event, ...args)(event: string, ...args: unknown[]) => void- Invoke every listener registered for
event, passing through all additional arguments. .off(event, listener)(event: string, listener: Function) => void- Remove a previously registered listener. Pass the same function reference used in
.on.
Returns
EventEmitter — An instance exposing .on, .emit, and .off. The methods themselves return void.
Examples
const ee = new EventEmitter();
ee.on("data", (msg) => console.log("got", msg));
ee.emit("data", "hello"); // logs: got helloconst ee = new EventEmitter();
const handler = (n) => console.log(n);
ee.on("tick", handler);
ee.emit("tick", 1); // logs: 1
ee.off("tick", handler);
ee.emit("tick", 2); // nothing — handler removedWhat it has to do
.on(event, listener)registers a listener callback..emit(event, ...args)calls all registered listeners with args..off(event, listener)unregisters a specific listener.
Notes
- Emitting an event with no listeners should be a no-op, not an error.
- Removing by reference means callers must hold on to the function they passed into
.on— anonymous arrow functions can't be unsubscribed.
Try it yourself· Edit the code, then press Run
Loading playground...
- 1.subscribes and emits event arguments
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
1 tests · +250 XP
Discussion
Sign in to postSign in to join the conversation.Sign in
No comments yet. Be the first to say something.