-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathEventBus.ts
41 lines (39 loc) · 1.04 KB
/
EventBus.ts
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
export default class EventBus {
private _eventTree: Record<string, any> = {}
/**
* 注册事件
* @param eventName 事件名称
* @param cb 回调方法
*/
on(eventName: string, cb: Function) {
const fns = this._eventTree[eventName];
if (Array.isArray(fns)) {
fns.push(cb);
} else {
this._eventTree[eventName] = [cb];
}
}
/**
* 触发事件
* @param eventName 事件名称
* @param payload 传递参数
*/
emit(eventName: string, ...payload: any) {
const fns = this._eventTree[eventName];
if (Array.isArray(fns)) {
fns.forEach((fn) => fn(...payload));
}
}
/**
* 注销事件
* @param eventName 事件名称
* @param cb 传递参数
*/
off(eventName: string, cb: Function) {
const fns = this._eventTree[eventName];
const index = fns.find((fn: Function) => fn === cb);
if (Array.isArray(fns) && index) {
fns.splice(index, 1);
}
}
}