Access collection on two views in backbone.js

Go To StackoverFlow.com

0

Hi i have a collection and two views. On my view1 i'm adding data to my collection and view2 will just render and display any changes about the collection. But i can't get it to work. The problem is originally i'm doing this

return new CartCollection(); 

But they say its a bad practice so i remove changed it. But when i instantiate cart collection on view1 it would add but it seems view2 doesn't sees the changes and renders nothing.

Any ideas?

here is my cart collection.

define([
 'underscore',
 'backbone',
 'model/cart'
], function(_, Backbone, CartModel) {
var CartCollection = Backbone.Collection.extend({
model : CartModel,
initialize: function(){
}
});
return CartCollection;
});

Here is my itemView ( view1 )

AddToCart:function(ev){
    ev.preventDefault();
    //get data-id of the current clicked item
    var id = $(ev.currentTarget).data("id");
    var item = this.collection.getByCid(id);
    var isDupe = false;
    //Check if CartCollection is empty then add
    if( CartCollection.length === 0){
        CartCollection.add([{ItemCode:item.get("ItemCode"),ItemDescription:item.get("ItemDescription"),SalesPriceRate:item.get("RetailPrice"),ExtPriceRate:item.get("RetailPrice"),WarehouseCode: "Main",ItemType : "Stock",LineNum:1 }]);
    }else{
        //if check if the item to be added is already added, if yes then update QuantityOrdered and ExtPriceRate
        _.each(CartCollection.models,function(cart){
            if(item.get("ItemCode") === cart.get("ItemCode")){
                isDupe = true;
                var updateQty = parseInt(cart.get("QuantityOrdered"))+1;
                var extPrice = parseFloat(cart.get("SalesPriceRate") * updateQty).toFixed(2);
                cart.set({ QuantityOrdered: updateQty });
                cart.set({ ExtPriceRate: extPrice });
            }
        });
        //if item to be added has no duplicates add new item
        if( isDupe == false){ 
            var cartCollection = CartCollection.at(CartCollection.length - 1);
            var lineNum = parseInt( cartCollection.get("LineNum") ) + 1;
            CartCollection.add([{ItemCode:item.get("ItemCode"),ItemDescription:item.get("ItemDescription"),SalesPriceRate:item.get("RetailPrice"),ExtPriceRate:item.get("RetailPrice"),WarehouseCode: "Main",ItemType : "Stock",LineNum:lineNum}]); 
            }
    }
    CartListView.render();
}

My cartview (view2)

render: function(){
  this.$("#cartContainer").html(CartListTemplate);
  var CartWrapper = kendobackboneModel(CartModel, {
     ItemCode: { type: "string" },
     ItemDescription: { type: "string" },
     RetailPrice: { type: "string" },
     Qty: { type: "string" },
  });
  var CartCollectionWrapper = kendobackboneCollection(CartWrapper);
  this.$("#grid").kendoGrid({
    editable: true,
    toolbar: [{ name: "save", text: "Complete" }],
    columns: [
        {field: "ItemDescription", title: "ItemDescription"},
        {field: "QuantityOrdered", title: "Qty",width:80},
        {field: "SalesPriceRate", title: "UnitPrice"},
        {field: "ExtPriceRate", title: "ExtPrice"}
    ],
    dataSource: {
      schema: {model: CartWrapper},
      data: new CartCollectionWrapper(CartCollection),
     }
  });

},
2012-04-04 01:28
by jongbanaag
How do you pass the reference to the CartCollection instance between the two views? This is probably where the issue is - Chris Herring 2012-04-04 07:02
i'm not really sure but i just added this code on both views. var cartcollection = new CartCollection(); am i doing it right - jongbanaag 2012-04-04 07:17


7

The problem is you've created 2 different instances of CartCollection. So when you update or fetch data into one instance the other does not change but remains the same.

Instead you need to use the same instance of CartCollection across the 2 views (or alternatively keep the 2 insync) .Assuming both views are in the same require.js module you would need to:

1) Instantiate the CartCollection instance and store it somewhere that both views have access to. You could put this in the Router, the parent view, or anywhere else really. e.g.

var router = Backbone.Router.extend({});
router.carts = new CartCollection();

2) You need need to pass the CartCollection instance to each of your views. e.g.

var view1 = new ItemView({ collection: router.carts });
var view2 = new CartView({ collection: router.carts });

You may also want to just pass the Cart model to the CartView instead of the entire collection. e.g.

var cartModel = router.carts.get(1);
var view2 = new CartView({ model: cartModel });
2012-04-04 07:49
by Chris Herring
Ads