Last active
May 10, 2024 14:54
-
-
Save tbranyen/50c6a959f34b0fa33a3b26f4d88f2a49 to your computer and use it in GitHub Desktop.
Rethinking events using ES6 (https://tbranyen.com/events)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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