Vue 面试题及答案

学习 Vue 中观察者模式

2020-09-15  本文已影响0人  阿畅_

贴一个 Vue 中源码的观察者模式源码

image.png

手动实现观察者模式

// 发布者-目标
class Dep {
  constructor() {
    // 记录所有的订阅者
    this.subs = []
  }
  // 添加订阅者
  addSub(sub) {
    // 判断订阅者是否存在,并且有update 方法
    if (sub && sub.update) {
      this.subs.push(sub)
    }
  }
  // 发布通知
  notify() {
    // 循环发布通知
    this.subs.forEach(s => {
      s.update()
    })
  }
}

// 订阅者-观察者
class Watcher {
  update() {
    console.log('update --->')
  }
}

let dep = new Dep
let watcher = new Watcher
// 添加订阅者
dep.addSub(watcher)
// 发布执行
dep.notify()

// 执行结果 update --->

观察者模式和订阅发布模式的区别

上一篇 下一篇

猜你喜欢

热点阅读