对属性值直接监听
对属性进行直接监听,通过创建dep=new Set,Set内可以add添加对象类型,并确保dep为唯一的不重复对象。
示例图:
代码:
let price = 10,
quantity = 4,
total = 0;
let dep = new Set();
const effect = () => {
total = price * quantity;
};
const track = () => {
dep.add(effect);
};
const trigger = () => {
if (dep) {
dep.forEach(effect => effect());
}
};
track();
trigger();
console.log('总价格total: ' + total);
quantity = 9;
trigger();
console.log('总价格total: ' + total);
price = 13;
trigger();
console.log('总价格total: ' + total);