koel/resources/assets/js/utils/eventBus.ts

30 lines
754 B
TypeScript
Raw Normal View History

2022-04-15 14:24:30 +00:00
import { EventName } from '@/config'
export const eventBus = {
2022-04-15 17:00:08 +00:00
all: new Map(),
2022-04-15 14:24:30 +00:00
on (name: EventName | EventName[] | Partial<{ [K in EventName]: Closure }>, callback?: Closure) {
2022-04-23 22:01:40 +00:00
if (Array.isArray(name)) {
name.forEach(k => this.on(k, callback))
return
}
2022-04-15 14:24:30 +00:00
if (typeof name === 'object') {
2022-04-15 17:00:08 +00:00
for (const k in name) {
2022-04-15 14:24:30 +00:00
this.on(k as EventName, name[k as EventName])
}
return
}
2022-05-14 15:13:29 +00:00
this.all.has(name) ? this.all.get(name).push(callback) : this.all.set(name, [callback])
2022-04-15 14:24:30 +00:00
},
2022-04-15 17:00:08 +00:00
emit (name: EventName, ...args: any) {
2022-04-15 14:24:30 +00:00
if (this.all.has(name)) {
this.all.get(name).forEach((cb: Closure) => cb(...args))
2022-04-15 17:00:08 +00:00
} else {
console.warn(`Event ${name} is not listened by any component`)
2022-04-15 14:24:30 +00:00
}
}
}