eventBus.uts
1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* 全局事件总线
* 用于跨组件通信,解耦业务逻辑
*
* 使用方式:
* import { eventBus } from "@/utils/eventBus.uts"
* eventBus.emit('xxx', data)
*/
type EventBusCallback = (data?: any) => void
export class EventBus {
private static instance: EventBus | null = null
private listeners: Map<string, Array<EventBusCallback>> = new Map()
static getInstance(): EventBus {
if (EventBus.instance == null) {
EventBus.instance = new EventBus()
}
return EventBus.instance
}
/**
* 订阅事件
* @param event 事件名称
* @param callback 回调函数
*/
on(event: string, callback: EventBusCallback): void {
let callbacks = this.listeners.get(event)
if (callbacks == null) {
callbacks = []
this.listeners.set(event, callbacks)
}
callbacks.push(callback)
console.log(`[EventBus] 订阅事件: ${event}, 当前监听器数量: ${callbacks.length}`)
}
/**
* 取消订阅
* @param event 事件名称
* @param callback 回调函数
*/
off(event: string, callback: EventBusCallback): void {
const callbacks = this.listeners.get(event)
if (callbacks != null) {
const index = callbacks.indexOf(callback)
if (index >= 0) {
callbacks.splice(index, 1)
console.log(`[EventBus] 取消订阅: ${event}`)
}
}
}
/**
* 发布事件
* @param event 事件名称
* @param data 事件数据
*/
emit(event: string, data?: any): void {
const callbacks = this.listeners.get(event)
if (callbacks != null && callbacks.length > 0) {
for (const cb of callbacks) {
try {
cb(data)
} catch (error) {
console.error(`[EventBus] 事件回调执行失败: ${event}`, error)
}
}
} else {
console.warn(`[EventBus] 事件无监听器: ${event}`)
}
}
/**
* 清空所有监听器(用于调试或重置)
*/
clearAll(): void {
this.listeners.clear()
console.log('[EventBus] 已清空所有监听器')
}
}
// 导出单例实例
export const eventBus = EventBus.getInstance()
export default eventBus