javascript - Access collection on two views in backbone.js - Stack Overflow

Hi i have a collection and two views. On my view1 i'm adding data to my collection and view2 will

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),
     }
  });

},

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),
     }
  });

},
Share Improve this question asked Apr 4, 2012 at 1:28 n0minaln0minal 3,2259 gold badges50 silver badges72 bronze badges 2
  • How do you pass the reference to the CartCollection instance between the two views? This is probably where the issue is. – Chris Herring Commented Apr 4, 2012 at 7:02
  • i'm not really sure but i just added this code on both views. var cartcollection = new CartCollection(); am i doing it right? – n0minal Commented Apr 4, 2012 at 7:17
Add a ment  | 

1 Answer 1

Reset to default 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 });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745184808a4615585.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信