Typed Event Emitter With Once Off

Create a typed event emitter supporting on once off and emit with listener count introspection for decoupled communication.

JavascriptData Integrity

Code

javascriptsnippet
1 line
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

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`.