1 changed files with 57 additions and 0 deletions
@ -0,0 +1,57 @@ |
|||
type EventCallback = (...args: any[]) => void; |
|||
|
|||
class EventBus { |
|||
private events: Map<string, Set<EventCallback>> = new Map(); |
|||
|
|||
on(event: string, callback: EventCallback): () => void { |
|||
if (!this.events.has(event)) { |
|||
this.events.set(event, new Set()); |
|||
} |
|||
this.events.get(event)!.add(callback); |
|||
|
|||
// 返回取消订阅函数
|
|||
return () => this.off(event, callback); |
|||
} |
|||
|
|||
off(event: string, callback: EventCallback): void { |
|||
const callbacks = this.events.get(event); |
|||
if (callbacks) { |
|||
callbacks.delete(callback); |
|||
if (callbacks.size === 0) { |
|||
this.events.delete(event); |
|||
} |
|||
} |
|||
} |
|||
|
|||
once(event: string, callback: EventCallback): () => void { |
|||
const onceCallback: EventCallback = (...args) => { |
|||
callback(...args); |
|||
this.off(event, onceCallback); |
|||
}; |
|||
return this.on(event, onceCallback); |
|||
} |
|||
|
|||
emit(event: string, ...args: any[]): void { |
|||
const callbacks = this.events.get(event); |
|||
if (callbacks) { |
|||
callbacks.forEach(cb => { |
|||
try { |
|||
cb(...args); |
|||
} catch (e) { |
|||
console.error(`EventBus: error in event "${event}"`, e); |
|||
} |
|||
}); |
|||
} |
|||
} |
|||
|
|||
clear(): void { |
|||
this.events.clear(); |
|||
} |
|||
|
|||
getEventCount(): number { |
|||
return this.events.size; |
|||
} |
|||
} |
|||
|
|||
export const eventBus = new EventBus(); |
|||
export default eventBus; |
|||
Loading…
Reference in new issue