1.發佈訂閱在很多地方很常見,其原理就是把想要執行的方法放到數組裏面去,然後遍歷數組執行裏面的方法
其中把方法添加到數據叫訂閱
遍歷數組執行裏面的方法叫發佈
接下來,上代碼
//發佈訂閱
function Dep(){
this.subs=[]
}
//訂閱
Dep.prototype.addSub=function(sub){
this.subs.push(sub)
}
//執行
Dep.prototype.notify=function(){
this.subs.forEach((item)=>{
item.update()
})
}
//一個類,可以叫觀察者
function Watch(fn){
this.fn=fn
}
Watch.prototype.update=function(){
this.fn()
}
let watcher=new Watch(()=>{
console.log(1)
})
let dep = new Dep()
dep.addSub(watcher) //訂閱一次
dep.addSub(watcher) //再訂閱一次
dep.addSub(watcher) //再訂閱一次,最後這個方法會執行三次
dep.notify()