Event Emitter With Once And Off Semantics
A small event emitter that adds one-shot listeners, removal by original callback, snapshot dispatch and listener counts without Node dependencies.
Code
export class EventEmitter {
#listeners = new Map();
on(event, listener) {
if (typeof event !== "string" || event.length === 0) {
throw new TypeError("event must be a non-empty string");
}
if (typeof listener !== "function") {
throw new TypeError("listener must be a function");
}
let bucket = this.#listeners.get(event);
if (!bucket) {
bucket = new Set();
this.#listeners.set(event, bucket);
}
bucket.add(listener);
return () => this.off(event, listener);
}
once(event, listener) {
const wrapper = (...args) => {
this.off(event, wrapper);
listener(...args);
};
wrapper.original = listener;
return this.on(event, wrapper);
}
off(event, listener) {
const bucket = this.#listeners.get(event);
if (!bucket) return false;
let removed = false;
for (const entry of bucket) {
if (entry === listener || entry.original === listener) {
bucket.delete(entry);
removed = true;
}
}
if (bucket.size === 0) this.#listeners.delete(event);
return removed;
}
emit(event, ...args) {
const bucket = this.#listeners.get(event);
if (!bucket) return false;
for (const listener of [...bucket]) listener(...args);
return true;
}
listenerCount(event) {
return this.#listeners.get(event)?.size ?? 0;
}
removeAllListeners(event) {
if (event === undefined) this.#listeners.clear();
else this.#listeners.delete(event);
}
}How the snippet works
Event Emitter With Once And Off Semantics keeps everything in the class EventEmitter and the function wrapper.
The structure is a loop within a loop: for (const entry of bucket) outside, for (const listener of [...bucket]) listener(...args); inside. Failure is loud: TypeError aborts the current operation instead of degrading it.
Points of care
- The guard
typeof event !== "string" || event.length === 0short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The surface worth importing is EventEmitter; the helpers around it are private to the snippet.
Statements that matter
return this.#listeners.get(event)?.size ?? 0;
return () => this.off(event, listener);
throw new TypeError("event must be a non-empty string");
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.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- How does the snippet fail?
- The code refuses to continue: `TypeError` is thrown while the state is still recoverable.
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `wrapper` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.