event-bus
# event-bus
// Event bus
// 发布订阅设计模式的应用,node.js 的基础模块,也是前端组件通信的一种手段,比如Vue的$on和$emit
function EventBus() {
// 以事件名为key,事件处理函数组成的数组为value
this.events = {}
}
module.exports = EventBus
// 监听事件
// eventName 事件名
// cb 事件处理函数
EventBus.prototype.$on = function(eventName, cb) {
if (!Array.isArray(cb)) {
cb = [cb]
}
this.events[eventName] = (this.events[eventName] || []).concat(cb)
}
EventBus.prototype.$emit = function(eventName, ...args) {
this.events[eventName].foEach(fn => {
fn.apply(this, args)
})
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25