ChickenDreamFactory/fe-chicken

57.event-bus

Opened this issue · 0 comments

// 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)
}

Event.prototype.$emit = function(eventName, ...args) {
 this.events[eventName).forEach(fn => {
   fn.apply(this, args)
 })
}