A tiny event emitter
Publish and subscribe to named events in about 15 lines, with an unsubscribe function returned from on().
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
function createEmitter() {
const handlers = new Map();
return {
on(event, handler) {
if (!handlers.has(event)) handlers.set(event, new Set());
handlers.get(event).add(handler);
return () => handlers.get(event)?.delete(handler);
},
emit(event, ...args) {
for (const handler of [...(handlers.get(event) ?? [])]) handler(...args);
},
};
}Example / expected output
const bus = createEmitter();
const off = bus.on("saved", (id) => console.log("saved", id));
bus.emit("saved", 42);
off();How it works
Returning the unsubscribe function from on avoids having to keep a reference to the handler. Handlers are copied before emitting, so a handler that unsubscribes itself does not cause the next one to be skipped.
Related snippets
- TypeScript Tested
Type-safe event emitter
An event emitter whose event names and payloads are checked by the compiler through a generic map type.
- JavaScript Tested
Remove duplicates from an array
Deduplicate primitives with a Set, or objects by a key or computed value, keeping the first occurrence.
- JavaScript Tested
Truncate a string with an ellipsis
Shorten text to a maximum length without cutting in the middle of a word or a Unicode character.
- JavaScript Tested
Sort an array by multiple keys
Sort objects by one field, then break ties with another, with ascending or descending order per field.

