eventbus.js
1.82 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
class Bus {
constructor() {
this.events = {};
}
/**
* 订阅事件
* @param {string} event - 事件名称
* @param {Function} callback - 回调函数
*/
on(event, callback) {
if (typeof event !== 'string') {
console.error('Event name must be a string');
return;
}
if (typeof callback !== 'function') {
console.error('Callback must be a function');
return;
}
if (this.events[event]) {
this.events[event].push(callback);
} else {
this.events[event] = [callback];
}
// 如果是匿名函数就给用户个警告
if (!callback.name) {
console.warn('on 接口的 handler 参数推荐使用具名函数。具名函数可以使用 off 接口取消订阅,匿名函数无法取消订阅。');
}
}
/**
* 触发事件
* @param {string} event - 事件名称
* @param {*} data - 传递给回调函数的数据
*/
emit(event, data) {
if (!this.events[event]) return;
this.events[event].forEach(callback => {
if (typeof callback === 'function') {
callback(data);
}
});
}
/**
* 取消订阅事件
* @param {string} event - 事件名称
* @param {Function} callback - 要取消的回调函数
*/
off(event, callback) {
if (!this.events[event]) return;
if (typeof callback !== 'function') {
console.error('Callback must be a function');
return;
}
const index = this.events[event].findIndex(item => item === callback);
if (index !== -1) {
this.events[event].splice(index, 1);
}
}
/**
* 获取单例实例
* @returns {Bus} Bus类的单例实例
*/
static getInstance() {
if (!Bus.instance) {
Bus.instance = new Bus();
}
return Bus.instance;
}
}
// 导出Bus类的单例实例
export default Bus.getInstance();