{
let target = null;
class Dep {
constructor() {
this.subscribers = [];
}
depend() {
if (target && !this.subscribers.includes(target)) {
this.subscribers.push(target);
}
}
notify() {
this.subscribers.forEach((sub) => sub());
}
}
let data = {
price: 20,
amount: 5
};
let deps = new Map();
Object.keys(data).forEach((key) => {
deps.set(key, new Dep());
});
let data_without_proxy = data;
data = new Proxy(data_without_proxy, {
get(obj, key) {
deps.get(key).depend();
return obj[key];
},
set(obj, key, newVal) {
obj[key] = newVal;
deps.get(key).notify();
return true;
}
});
function watcher(fn) {
target = fn;
target();
target = null;
}
let total;
watcher(() => {
total = data.price * data.amount;
});
const ret = [total];
data.price = 30;
ret.push(total);
return ret;
}