Event Bus
2024-11-17 13:58:59
EventBus.ts
test.ts
class EventBus<T extends Record<string, (...args: any[]) => void>> {
private events: Map<keyof T, Set<T[keyof T]>>
constructor() {
this.events = new Map()
}
on<K extends keyof T>(name: K, callback: T[K]) {
if (!this.events.has(name)) {
this.events.set(name, new Set())
}
this.events.get(name)?.add(callback)
}
emit<K extends keyof T>(name: K, ...args: Parameters<T[K]>) {
if (this.events.has(name)) {
this.events.get(name)?.forEach(cb => cb(...args))
}
}
off<K extends keyof T>(name: K, callback?: T[K]) {
if (this.events.has(name)) {
if (callback) this.events.get(name)?.delete(callback)
else this.events.delete(name)
}
}
once<K extends keyof T>(name: K, callback: T[K]) {
const once = (...args: any[]) => {
callback(...args)
this.off(name, once as T[K])
}
this.on(name, once as T[K])
}
}