Reputation: 3223
I need to click items on ItemCollection and transfer it to CartCollection. But i can't get it to work. I need to get the model of the currentTarget clicked by the user. Any ideas? I commented out a CartCollection.add just to test it.
define([
'jquery',
'underscore',
'backbone',
'model/item_model',
'model/cart_model',
'collection/item_collection',
'collection/cart_collection',
'view/cart/cartlist_view',
'text!templates/items/itemlist.html'
],function($, _, Backbone, Item, Cart, ItemCollection, CartCollection, CartListView, ItemListTemplate){
var ItemListView = Backbone.View.extend({
el: $("#mainContainer"),
events:{
"click #itemListContainer li" : "AddToCart"
},
initialize: function(){
this.model = Item;
this.collection = ItemCollection;
this.collection.bind("reset", this.render );
CartCollection.bind("add", CartListView.render());
},
render: function(){
var data = {
items: ItemCollection.models,
item: Item
}
var compiledTemplate = _.template( ItemListTemplate , data);
$("#itemContainer").html( compiledTemplate );
},
AddToCart:function(ev){
ev.preventDefault();
// CartCollection.add([
// {ItemCode:"item-12312",ItemDescription:"OldSomething",RetailPrice:"2",Qty:"1"},
// {ItemCode:"item-12122",ItemDescription:"OldSometh21g",RetailPrice:"4",Qty:"2"}
// ]);
// var code = $(ev.currentTarget).data("ItemCode");
// var test = CartCollection.get(code);
// var name = test.get("ItemDescription");
CartListView.render();
alert($(ev.currentTarget).text());
}
});
return new ItemListView;
});
Upvotes: 0
Views: 627
Reputation:
Alt A: Create a view for each sub item holding the model
When rendering chart items you can add this to a sub view where you pass model and a callback. The callback is called by each subview when it is clicked:
ItemView({
model: item,
onAdd: this.AddToCart
});
In subview:
events: {
"click": "onClick"
},
onClick: function(){
this.options.onAdd(this.model);
}
In parent view:
AddToCart: function(model){
//Do what you what you want with the item
}
Alt B: Add the model id to the li
item and get it from a item collection
<li><a href="#" data-id="<%=item.id%>">An item</a></li>
And then get the model from the items collection:
var id = $(e.currentTarget).data("id");
var item = items.get(id);
Upvotes: 1