js实现简单的中央事件总线EventBus
在vue中会用到中央事件总线进行小型项目的组件通信,这里用js简单实现一个,学习记录,有不足之处可指出
class EventBus {
constructor() {
this.eventList = new Map()
}
on(name,fn) {
this.eventList.set(name,fn)
}
emit(eName, data) {
const cb = this.eventList.get(eName)
if(cb) {
cb(data)
} else{
throw new Error('no Registration event')
}
}
remove(eName) {
this.eventList.delete(eName)
}
}
const a = new EventBus()
a.on('handleKeyword',(value)=> {
console.log('接收到handleKeyword:', value)
})
a.on('suc',(value)=> {
console.log('接收到suc:', value)
})
a.emit('handleKeyword', 'hello')
a.emit('suc', 'suchello')
a.emit('suc', 'suchello11')
a.remove('suc')
a.emit('suc', 'suchello')