1、发布订阅模式
在此模式中最突出的事件中心类,而并不关注发布者与订阅者是谁。
//事件中心类
class eventEmitter{
constructor(){
//事件存储器
this.subs={}
}
//注册事件
$on(eventType,handler){
this.subs[eventType]=this.subs[eventType]||[]
this.subs[eventType].push(handler)
}
//触发事件
$emit(eventType){
if(this.subs[eventType]){
this.subs[eventType].forEach(handler=>{
handler()
})
}
}
}
let em=new eventEmitter()
em.$on('click',function(){console.log('事件触发了1')})
em.$on('click',function(){console.log('事件触发了2')})
em.$emit('click')
2、观察者模式
在此模式中没有事件中心,并且发布者需要知道订阅者的存在,在Vue中,数据变化时,会触发观察者的updata方法,达到视图更新
观察者(订阅者)Watcher
updata() //当事件发生时,要做的事情。
目标(发布者)Dep
subs 数组,存储所有的观察者
addSubs() //添加观察者
notify()当事件发生时,调用所有的观察者的updata()方法
没有事件中心
//发布者-目标
class Dep{
constructor(){
//记录所有的订阅者
this.subs=[]
}
addSub(sub){
if(sub&&sub.updata){
this.subs.push(sub)
}
}
notify(){
this.subs.forEach(sub=>{
sub.updata()
})
}
}
//订阅者-观察者
class Watcher{
updata(){
console.log('updata')
}
}
let dep=new Dep()
let watcher=new Watcher()
dep.addSub(watcher)
dep.notify()
总结
1、观察者模式是由具体目标调度,当事件发生时,会调度Dep中的观察者的方法,所以观察者模式中的观察者与发布者之间是存在依赖的。
2、发布订阅模式由统一调度中心调用,因此发布者与订阅者不需要知道对方的存在