Typed Event Emitter With Once Off
Create a typed event emitter supporting on once off and emit with listener count introspection for decoupled communication.
Code
export function createEmitter(){const listeners=new Map();function on(event,handler){if(!listeners.has(event))listeners.set(event,new Set());listeners.get(event).add(handler);return()=>off(event,handler);}function once(event,handler){const w=(...a)=>{off(event,w);handler(...a);};return on(event,w);}function off(event,handler){listeners.get(event)?.delete(handler);}function emit(event,...a){const s=listeners.get(event);if(s)for(const h of[...s])h(...a);}on.listenerCount=(e)=>listeners.get(e)?.size??0;return{on,once,off,emit};}How it works
Count the functions w, createEmitter, on and once as the entire surface area of Typed Event Emitter With Once Off.
The result comes back as an object carrying on, once, off.
Applying it
The main signature reads export function createEmitter()
Import createEmitter from the file and call it — the rest of the code is implementation detail.
The call returns on, once, off — destructure what you need at the call site.
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.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. The file defines `w`, `createEmitter`, `on` at load time.
- What does `createEmitter` return?
- An object carrying `on`, `once`, `off`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.