Code library

Free snippets & functions

Copy, adapt and use them in your own projects.

JavaScript · An event emitter classAdvanced
class Emitter {
  #map = new Map();

  on(type, fn) {
    (this.#map.get(type) ?? this.#map.set(type, new Set()).get(type)).add(fn);
    return () => this.off(type, fn);
  }
  once(type, fn) {
    const off = this.on(type, (...a) => { off(); fn(...a); });
    return off;
  }
  off(type, fn) { this.#map.get(type)?.delete(fn); }
  emit(type, ...args) { [...(this.#map.get(type) ?? [])].forEach((fn) => fn(...args)); }
}

const e = new Emitter();
let hits = 0;
e.once('ping', () => hits++);
e.emit('ping'); e.emit('ping');

on, once, off and emit in about twenty lines. The base of most small frameworks.