js中发布订阅模式示例

发布订阅模式

function Dep() {
  this.subs = []
}
Dep.prototype.addsub = function (sub) {
  this.subs.push(sub)
}
Dep.prototype.notify = function () {
  this.subs.forEach(sub => sub.update())
}

function Watcher(fn) {
  this.fn = fn
}
Watcher.prototype.update = function () {
  this.fn()
}
let watcher = new Watcher(function () {
  console.log(1)
})

let dep = new Dep()
dep.addsub(watcher)
console.log(dep.subs)
dep.notify()

 

你可能感兴趣的:(js)