Minimal Typed Event Emitter
Build a small publish and subscribe emitter that registers listeners per event name and supports one-shot subscribers and clean removal.
Code
export class EventEmitter {
constructor() {
this.listeners = new Map();
}
on(event, handler) {
const set = this.listeners.get(event) ?? new Set();
set.add(handler);
this.listeners.set(event, set);
return () => this.off(event, handler);
}
once(event, handler) {
const off = this.on(event, (payload) => {
off();
handler(payload);
});
return off;
}
off(event, handler) {
const set = this.listeners.get(event);
if (set) set.delete(handler);
}
emit(event, payload) {
const set = this.listeners.get(event);
if (!set) return 0;
for (const handler of [...set]) handler(payload);
return set.size;
}
}How it works
The working surface is the class EventEmitter — everything else is wiring.
Iteration happens inside for (const handler of [...set]) handler(payload); — everything outside it runs once.
Points of care
- The guard
!setshort-circuits the flow with an earlyreturnwhen its condition holds.
Using it
EventEmitter is the public entry point; everything else in the file exists to support it.
Key statements
const set = this.listeners.get(event) ?? new Set();
return () => this.off(event, handler);
const off = this.on(event, (payload) => {
off();
handler(payload);
});
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.