发布订阅模式
一定是先有的订阅,然后才会发布,让订阅的接收到发布的内容。
订阅会将函数放入数组中:[fn1,fn2,fn3]。然后发布的时候让数组中的函数一次执行。
1.实现发布订阅
- addSub将函数放入数组中就是订阅功能
- notify让数组中的函数一次执行就是发布功能
function Dep() {
this.subs=[];
}
//订阅
Dep.prototype.addSub=function (sub) {
this.subs.push(sub);
}
//sub中都有一个update属性,当需要sub执行的时候执行sub中的update方法
Dep.prototype.notify=function () {
this.subs.forEach(sub=>sub.update())
}
2.创建实例需要被订阅的构造函数
通过Watcher创建的实例都可以被订阅,当发布的时候可以执行update中的方法。
function Watcher(fn) {//Watcher是一个类 通过这个类创建的实例都拥有update方法
this.fn=fn;
}
Watcher.prototype.update=function () {
this.fn();
}
let watcher=new Watcher(function () { //监听函数
console.log(1)
})
3.执行发布订阅
let dep=new Dep();
dep.addSub(watcher);//订阅上 将watcher放到数组中 [watcher]
dep.addSub(watcher);//订阅上 将watcher放到数组中 [watcher,watcher]
dep.notify();// 发布