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
|
|
|
|
2022-04-15 17:00:08 +00:00
|
|
|
on (name: EventName | Partial<{ [K in EventName]: TAnyFunction }>, callback?: TAnyFunction) {
|
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-04-15 17:00:08 +00:00
|
|
|
if (this.all.has(name)) {
|
|
|
|
this.all.get(name).push(callback)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
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)) {
|
2022-04-15 17:00:08 +00:00
|
|
|
this.all.get(name).forEach((cb: TAnyFunction) => cb(...args))
|
|
|
|
} else {
|
|
|
|
console.warn(`Event ${name} is not listened by any component`)
|
2022-04-15 14:24:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|