我正在设置一个用于将商品添加到购物车的类。购物车项目存储在 Map() 中。现在我想在每次更改地图时将项目保存为 cookie。因此,当我调用 map.set() 或 map.delete() 时,我想触发保存功能。但我想自动调用它,而不是在发生“更改内容”的每一行代码中。
我已经尝试过使用代理,但由于我至少需要支持 IE11,所以我无法使用它。
import Product from "./product";
export default class Cart {
constructor() {
this.items = new Map();
}
watchForChanges(id) {
// watch if this.item is changed
// call saveItem if is changed
}
saveItem () {
// save item
}
addItem(id, count, callback) {
if (this.items.has(id)) {
this.items.get(id).count += count;
callback( this.items.get(id) );
return true;
}
this.newItem(id, count, callback);
}
newItem(id, count, callback) {
let product = new Product(id);
product.then((resolvedProduct) => {
this.items.set(id, {} = resolvedProduct );
this.watchForChanges(id);
callback(this.items.get(id));
}).catch((reject) => {
Error("Network Error")
});
}
removeItem(id, count = this.items.get(id).count, callback) {
if (!this.items.has(id)) return false;
let newCount = this.items.get(id).count -= count;
if (newCount <= 0) this.items.delete(id);
callback();
}
//some more functions
}
现在我可以在每次更改某些内容时调用 saveItem() 。我如何创建类似于 eventListener 的东西来设置和删除 Map() 中的项目;?