Minimal Typed Event Emitter

Build a small publish and subscribe emitter that registers listeners per event name and supports one-shot subscribers and clean removal.

JavascriptResilience

Code

javascriptsnippet
32 lines
export class EventEmitter {
  constructor() {
    this.listeners = new Map();
  }

  on(event, handler) {
    const set = this.listeners.get(event) ?? new Set();
    set.add(handler);
    this.listeners.set(event, set);
    return () => this.off(event, handler);
  }

  once(event, handler) {
    const off = this.on(event, (payload) => {
      off();
      handler(payload);
    });
    return off;
  }

  off(event, handler) {
    const set = this.listeners.get(event);
    if (set) set.delete(handler);
  }

  emit(event, payload) {
    const set = this.listeners.get(event);
    if (!set) return 0;
    for (const handler of [...set]) handler(payload);
    return set.size;
  }
}

How it works

The working surface is the class EventEmitter — everything else is wiring.

Iteration happens inside for (const handler of [...set]) handler(payload); — everything outside it runs once.

Points of care

  • The guard !set short-circuits the flow with an early return when its condition holds.

Using it

EventEmitter is the public entry point; everything else in the file exists to support it.

Key statements

const set = this.listeners.get(event) ?? new Set();
return () => this.off(event, handler);
const off = this.on(event, (payload) => {
off();
handler(payload);
});

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it.