Created
April 2, 2024 08:47
-
-
Save flxxyz/e94de2e161c4c2e125567f455cca44f6 to your computer and use it in GitHub Desktop.
javascript event callbacks
This file contains 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
export type Callback = (...args: any[]) => any; | |
export class Callbacks { | |
#callbacks: Map<string, Callback[]>; | |
constructor() { | |
this.#callbacks = new Map(); | |
} | |
add(name: string, fn: any) { | |
const newCallbacks: Callback[] = []; | |
if (this.#callbacks.has(name)) { | |
const callbacks = this.#callbacks.get(name) as Callback[]; | |
newCallbacks.push(...[...callbacks, fn]); | |
} else { | |
newCallbacks.push(fn); | |
} | |
this.#callbacks.set(name, newCallbacks); | |
} | |
remove(name: string) { | |
this.#callbacks.delete(name); | |
} | |
run(name: string, ...args: any) { | |
const callbacks = this.#callbacks.get(name) as Callback[]; | |
return callbacks.reduce(async (p: any, fn: Callback) => { | |
p = await fn(...args); | |
return p; | |
}, undefined); | |
} | |
emit(name: string, ...args: any) { | |
const callbacks = this.#callbacks.get(name) as Callback[]; | |
callbacks.forEach(fn => fn(...args)); | |
} | |
} | |
export const callbacks = new Callbacks(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment