Search code examples
javascriptes6-map

How to look for changes in Map() when item is set or delete?


I am setting up a class for adding items to a shopping cart. The cart items are stored in a Map(). Now I want to save items as cookies, every time the map is changed. So when I call map.set() or map.delete() I want to fire a save function. But I want to call it automatically not in every line of code where "change stuff" is happening.

I already tried to use proxies but as I need to support at least IE11, I cant use it.

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



}

Right now I can call saveItem() every time i change something. How could I create something like a eventListener for setting and deleting items in Map(); ?


Solution

  • After some research: I found out that babel doesnt have polyfills for extending built in classes like https://babeljs.io/docs/en/caveats/#classes

    class MyMap extend Map {
    //...
    }
    

    What i do right now is a function for the prototype of Map() and call the a save function... not really nice but it works...

    constructor() {
    
        this.items = new Map();
        let onupdate = this;
        Map.prototype.setItem = function (key, val) {
          this.set(key, val);
          onupdate.saveItem();
          return true;
        }
    
        Map.prototype.deleteItem = function (key,) {
          this.delete(key);
          onupdate.saveItem();
          return true;
        }
    
    
      }