function observable(obj){
if(!obj || typeof obj !== 'object') {
return;
}
let keys = Object.keys(obj);
keys.forEach((key) => {
defineReactive(obj, key, obj[key])
})
return obj;
}
class Dep{
constructor(){
this.sub = []
},
//增加订阅者
addSub(sub){
this.subs.push(sub);
},
//判断是否增加订阅者
//通知订阅者更新
notify(){
this.subs.forEach((sub) => {
sub.update();
})
}
}
function defineReactive(obj, key, val){
let dep = new Dep();
observable(obj)
Object.defineProperty(obj, key, {
get(){
dep.addSub();
console.log(`${key}属性被读取了`);
return val;
},
set(newVal){
val = newVal;
console.log(`${key}属性被修改了`);
dep.notify();
}
}
}
let obj = {};
observable(obj);