JSFiddle - React, Tailwind, and code Playground

by dp0ch

JavaScript

function Event() {
  let handlers = {};
  let nextId = 0;

  function on(handler) {
    const id = nextId++;
    handlers[id] = handler;
    return () => delete handlers[id];
  }

  function emit(...args) {
    Object.values(handlers).forEach((f) => f(...args));
  }

  function once(handler) {
    const off = on((...args) => {
      handler(...args);
      off();
    });
    return off;
  }

  function clear() {
    handlers = {};
  }

  return {
    on,
    emit,
    once,
    clear,
    get listeners() {
      return Object.values(handlers);
    },
  };
}

const e = new Event();

e.on((...args) => console.log('on', ...args));
e.once((...args) => console.log('once', ...args))
const off = e.on((...args) => console.log('manual off', ...args));
e.emit(1);
e.emit(2);
off();
e.emit(3);
console.log(e.listeners);
e.clear();
e.emit(4);
console.log(e.listeners);