先上一个发布订阅的简单例子
//发布订阅模式 先有订阅再有发布
//有一个方法,可以订阅一些事件 这些事件会放在数组里 [fn1,fn2,fn3]
function Dep(){
this.subs = [];
}
//订阅的实现
Dep.prototype.addSub = function(sub){
this.subs.push(sub)
}
//发布的实现 绑定的方法,如[fn1,fn2,fn3] 都有一个update属性
Dep.prototype.notify = function(){
this.subs.forEach(sub=>sub.update())
}
//Watcher是一个类,通过这个类创建的实例,都拥update方法
function Watcher(fn){
this.fn = fn
}
Watcher.prototype.update = function(){
this.fn()
}
let watcher = new Watcher(function(){//监听函数
alert(1)
})
let dep = new Dep()
dep.addSub(watcher) //将watcher放到了数组中 [watcher.update]
dep.addSub(watcher) //将watcher放到了数组中 [watcher.update]
console.log(dep.subs)
dep.notify() //数组关系