Skip to content

Instantly share code, notes, and snippets.

@tbranyen
Last active July 30, 2023 09:33
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save tbranyen/50c6a959f34b0fa33a3b26f4d88f2a49 to your computer and use it in GitHub Desktop.
Save tbranyen/50c6a959f34b0fa33a3b26f4d88f2a49 to your computer and use it in GitHub Desktop.
Rethinking events using ES6 (https://tbranyen.com/events)
const bus = {};
const get = e => (bus[e] = bus[e] || new Set());
export const listeners = new Proxy(bus, { get });
export const emit = (e, ...args) => listeners[e].forEach(fn => fn(...args));
import { listeners, emit } from '//tbranyen.com/events';
// Simply name any property on listeners and it will become an event.
listeners.onUpdate.add(updated => console.log('Updated:', updated));
// Instruct an event to be emitted.
emit('onUpdate', 'Hello world');
// Clear all `onUpdate` events.
listeners.onUpdate.clear();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment