我需要点击ItemCollection上的项目并将其转移到CartCollection。但我无法让它发挥作用。我需要获取用户点击的currentTarget模型。有任何想法吗?我注释掉CartCollection.add只是为了测试它。
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;
});
答案 0 :(得分:1)
Alt A:为包含模型的每个子项创建一个视图
渲染图表项时,可以将其添加到传递模型和回调的子视图中。单击时,每个子视图都会调用回调:
ItemView({
model: item,
onAdd: this.AddToCart
});
在子视图中:
events: {
"click": "onClick"
},
onClick: function(){
this.options.onAdd(this.model);
}
在父视图中:
AddToCart: function(model){
//Do what you what you want with the item
}
替代B:将模型ID添加到li
项目并从项目集合中获取
<li><a href="#" data-id="<%=item.id%>">An item</a></li>
然后从项目集合中获取模型:
var id = $(e.currentTarget).data("id");
var item = items.get(id);