在vue中,我们有时会用eventBus进行简易组件通信,那么这个eventBus究竟是如何实现的呢?
eventBus其实是一个典型的观察订阅模式,我们需要实现:
1、订阅事件on
2、触发事件emit
3、移除事件off
思路还是很简单的,我们直接看一下代码:
class EventBus {
constructor(){
this.eventContainer = this.eventContainer || new Map() //用一个容器存放事件
}
on(type,callback){
if(!this.eventContainer.get(type)){
//如果容器里面没有这种类型的事件,就增加
this.eventContainer.set(type,callback)
}
}
off(type){
if(this.eventContainer.get(type)){
this.eventContainer.delete(type)
}
}
emit(type){
let fn = this.eventContainer.get(type)
fn.apply(this,[...arguments].slice(1))
}
}
let ev = new EventBus()
ev.on('myevent',name=>{console.log('hello,',name)})
ev.emit('myevent','jack')
转自
https://www.jianshu.com/p/acccc98ba1dc