订阅–观察者模式
先定义一个订阅管理器
class Dep{ // 订阅管理 [fn1, fn2, fn3...实例]
constructor(){
this.subs = []
}
addSub(sub){
this.subs.push(sub)
}
remove(sub){
let index = this.subs.indexOf(sub)
if (index<=-1) return
this.subs.splice(index, 1)
}
notify(){
if(this.subs.length<=0) return
this.subs.forEach((sub)=>{
sub.update()
})
}
}
在定义一个定义管理者类,用以声明具体的实例
class Watcher{ // 订阅者的类---用于实例化的类
constructor(fn){ // fn就是要接收的信息
this.fn = fn
}
update(){
this.fn()
}
}
然后添加订阅者,发布消息
function newNews(){
console.log('新消息')
}
let dep = new Dep()
//订阅者
let person1 = new Watcher(newNews)
let person2 = new Watcher(newNews)
let person3 = new Watcher(newNews)
//订阅管理者添加订阅者
dep.addSub(person1)
dep.addSub(person2)
dep.addSub(person3)
//消息发布
dep.notify()