1

I have items that are stored as models through an add to cart button. The model has:

  • Name
  • Quantity
  • Item_ID

But it will not store duplicate items. If someone clicks on the add to cart button again I want the collection to merge the 2 models together by adding the quantities together but keeping the name/item_id the same.

I'd imagine I need to override the collection add function, to do specifically this when it sees a duplicate. Or is there some kind of method or parameter I can use when adding to my collection to do this for me?

var CartCollection = Backbone.Collection.extend({                   
    model: Item,
    add: function(newItem) {
      var dupeHandle = this.any(function(item) {
              if (item.get('name') === newItem.get('name')){
                  item.set('quantity', (item.get('quantity') + newItem.get('quantity'));
                  return true;
              }
      }
      if (dupeHandle) return;
      Backbone.Collection.add.call(this, item);
    } 
});
thesentyclimate413
  • 89
  • 3
  • 4
  • 11
  • 1
    Why are you adding it? Why not just update the `quantity` of the item in your collection that matches the `name`/`id` of the "added" item? – Nick Tomlin Jan 06 '15 at 00:46

0 Answers0