class Dep {
constructor(){
this.subscribers=[];
}
depend(){
if(target&&!this.subscribers.includes(target)){
this.subscribers.push(target);
}
}
notify(){
this.subscribers.forEach(sub => sub())
}
}
let target=null;
function watcher(myFunc) {
target=myFunc;
target();
target=null;
}
let data={
price:1,
quantity:2
};
// console.log(Object.keys(data));
Object.keys(data).forEach((key)=>{
let newVal=data[key];
const dep=new Dep();
Object.defineProperty(data,key,{
get(){
dep.depend();
return newVal
},
set(val){
newVal=val;
dep.notify();
}
})
});
total = data.price * data.quantity;
watcher(() => {
data.total = data.price * data.quantity
});
data.price=1;
console.log(data.total);
data.price=2;
console.log(data.total);