【发布时间】:2015-01-04 00:41:21
【问题描述】:
我对 Backbone 很陌生,我正在为 Backbone.Collection 苦苦挣扎:
我有一份不同类别的产品清单(鞋子、衬衫、裤子……)。这个想法是当用户点击一个类别时,我正在更新我的集合中的 URL(例如:datas/shoes.json 变为 datas/shirts.json)并执行一个 collection.fetch() 以呈现我的新列表。
它确实有效,但我不知道为什么它不断触发“添加”、“删除”事件。这是我的代码,如果你看到奇怪的东西,请告诉我:
define([
"backbone",
],
function(Backbone)
{
var ProductsView = Backbone.View.extend({
el: "#products",
initialize:function(){
_.bindAll(this,"addItem","removeAll");
this.populate();
},
populate:function(){
this.collection = new ProductCollection();
this.listenTo(this.collection, 'add', this.addItem);
this.listenTo(this.collection, 'remove', this.removeAll);
this.collection.fetch();
},
addItem(todo){
var view = new ProductItemView({model: todo});
this.$el.append(view.render().el);
},
removeAll:function(){
this.$el.children().remove();
this.collection.url = "datas/shoes.json";
this.collection.fetch();
},
});
return ProductsView;
});
这是我的收藏
define([
"backbone",
"models/modules/products/ProductModel"
],
function(Backbone, ProductModel)
{
var ProductsCollection = Backbone.Collection.extend({
model : ProductModel,
url : "datas/shirts.json",
parse: function(response){
return response.products;
},
});
return ProductsCollection;
});
感谢您的帮助伙计们!!
如果不清楚,请告诉我,我会尽力澄清。
【问题讨论】:
-
您将在获取后为不在集合中的每个元素获取一个删除事件,但您已将删除事件绑定到
removeAll,这将执行另一次获取。这可能是导致事件不断发生的原因。
标签: loops backbone.js collections fetch