正如您在以下代码中看到的那样,我正在尝试使用从集合中获取和过滤的数据来初始化主干视图。此过滤器不起作用并返回所有项目:
app.ShopView = Backbone.View.extend({
el:$('#content'),
initialize: function(options) {
var that = this;
this.collection = new app.ShopProductsCollection();
this.collection.fetch().done(function(){
var filterType = _.filter(that.collection.models,function(item){
return item.get('category') === 'accessories';
})
that.collection.reset(filterType);
});
this.listenTo(this.collection, 'add', this.addOne);
},
render: function() {
this.$el.html(this.template());
this.addAll();
return this;
},
addAll: function() {
this.collection.each(this.addOne, this);
},
addOne: function(model) {
view = new app.ShopItemView({model: model});
view.render();
this.$el.append(view.el);
model.on('remove', view.remove, view);
}
});
让它与 JQuery $.when() 包装器和重置事件的侦听器一起工作以调用渲染方法,这是我的新初始化方法:
initialize: function(options) {
var that = this;
this.collection = new directory.ShopProductsCollection();
$.when(this.collection.fetch()).done(function(){
var filterType = _.filter(that.collection.models,function(item){
return item.get('category') === 'accessories';
})
that.collection.reset(filterType);
});
this.listenTo(this.collection, 'reset', this.render);
this.listenTo(this.collection, 'add', this.addOne);
},