Skip to content
GreenSnippets

A tiny event emitter

Publish and subscribe to named events in about 15 lines, with an unsubscribe function returned from on().

JavaScript
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

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.

  • TypeScript Tested

    Type-safe event emitter

    An event emitter whose event names and payloads are checked by the compiler through a generic map type.