//监听 + 变化
// 使用 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)
原文:https://www.cnblogs.com/zhuoyue0071/p/13906860.html