首页 > 其他 > 详细

vue响应式原理之订阅者模式

时间:2020-10-31 18:10:19      阅读:31      评论:0      收藏:0      [点我收藏+]

技术分享图片

//监听 + 变化
// 使用 Object.defineProperty函数

let a = Object.keys(obj).forEach(key => {
let value = obj[key]

Object.defineProperty(obj, key, {
  set(newValue) {
    console.log(‘监听‘ + key + ‘改变‘);
    value = newValue
    dep.notify(newValue)
  },
  get() {
    console.log(‘获取‘ + key + ‘的值‘);
    return value
  }
})

})

// 发布订阅者模式
// 依赖对象
class Dep{
constructor(){
this.subs = []
}

addSub(watcher){
  this.subs.push(watcher)
}

notify(newV){
  this.subs.forEach(i => {
    i.update(newV)
  })
}

}

// 订阅者
class Watcher{
constructor(name){
this.name = name
}

update(newV){
  console.log(this.name + ‘产生新变更===‘ + newV);
}

}

const dep = new Dep();

const w1 = new Watcher(‘张三‘)
dep.addSub(w1)
const w2 = new Watcher(‘李四‘)
dep.addSub(w2)
const w3 = new Watcher(‘王五‘)
dep.addSub(w3)

vue响应式原理之订阅者模式

原文:https://www.cnblogs.com/zhuoyue0071/p/13906860.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!