消息订阅与发布
# 功能
全局消息分配与接受 参考vue全局时间总线eventBus
# 使用
import bus from '@/utils/Dispatcher.js'
Bus.emit('eventName', params); // 发布
Bus.on('eventName', functionName); || Bus.on('eventName', (result) => {}); // 订阅
Bus.off('eventName', functionName); // 销毁
1
2
3
4
2
3
4
# 源码
var dispCbs = [];
var dispIns = [];
function Dispatcher() {
dispIns.push(this);
dispCbs.push({});
}
Dispatcher.prototype = {
on(type, cb) {
let cbtypes = dispCbs[dispIns.indexOf(this)];
let cbs = cbtypes[type] = cbtypes[type] || [];
if (!~cbs.indexOf(cb)) {
cbs.push(cb);
}
},
off(type, cb) {
let cbtypes = dispCbs[dispIns.indexOf(this)];
let cbs = cbtypes[type] = cbtypes[type] || [];
let curTypeCbIdx = cbs.indexOf(cb);
if (~curTypeCbIdx) {
cbs.splice(curTypeCbIdx, 1);
}
},
emit(type, ...args) {
let cbtypes = dispCbs[dispIns.indexOf(this)];
let cbs = cbtypes[type] = cbtypes[type] || [];
for (let i = 0; i < cbs.length; i++) {
cbs[i].apply(null, args);
}
}
};
export default new Dispatcher()
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
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
上次更新: 2023/11/13, 09:31:42