// 订阅和发布(依赖收集类)
class Dep {
constructor() {
this.subs = [];
}
shouji(sub) {
if (sub && !this.subs.includes(sub)) {
this.subs.push(sub);
}
}
notify() {
this.subs.forEach(sub => sub());
}
}
let Person = {
name: '张三',
age: '22'
};
let target = null;
let info = '';
Object.keys(Person).forEach((key) => {
let value = Person[key];
let dep = new Dep();
Object.defineProperty(Person, key, { // 数据劫持
// 通过getter进行依赖收集,而每个setter方法就是一个观察者,在数据变更的时候通知订阅者更新视图
get() {
dep.shouji(target);
return value;
},
set(val) {
value = val;
dep.notify();
}
})
})
// 封装一个watcher函数. 帮你观察记录相关target事件,避免多次声明变量
function Watcher(myFunc) {
target = myFunc;
target();
target = null;
}
Watcher(() => {
info = `${Person.name}今年${Person.age}岁了`;
})
console.log(info);
Person.name = 'zhangpj';
Person.age = '28';
console.log(info)
网友评论