事件总线 EventBus
TODO: Vue 中的用法
const eventBus = new Vue();
eventBus.$on('event', (e) => {...});
eventBus.$emit('event', ...params);
eventBus.$off('event');
1
2
3
4
5
6
7
8
9
实现EventBus
Class EventBus {
constructor(){
this.events = {};
}
$on(eventName, callback, isOnce) {
const callbackArr = this.events[eventName];
if(!callbackArr){
this.events[eventName] = [];
}
this.events[eventName].push({callback, isOnce});
}
$emit(eventName, ...args) {
const callbackArr = this.events[eventName];
if(callbackArr) {
this.events[eventName] = callbackArr.filter({callback, isOnce} => {
callback.apply(this, args);
return !isOnce
})
}
}
$off(eventName, callback){
const callbackArr = this.events[eventName];
if(!callbackArr){
return;
}
if(callback){
this.events[eventName] = callbackArr.filter(item => item.callback !== callback)
}else{
this.events[eventName] = null;
}
}
$once(eventName, callback) {
this.on(eventName, callback, true);
}
}
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