我正在重构我的 Backbone.js 应用程序以使用 Marionette.js,并且我正试图将我的头脑围绕在一个CollectionView
.
假设我有几个ItemView
模型Cow
:
// Declare my models.
var Cow = Backbone.Model.extend({});
var Cows = Backbone.Collection.extend({
model: Cow
});
// Make my views
var GrassPatch = Marionette.ItemView.extend({
tagName: 'div',
template: "<section class='grass'>{{name}}</section>",
})
var Pasture = Marionette.CollectionView.extend({});
// Instantiate the CollectionView,
var blissLand = new Pasture({
itemView: GrassPatch;
});
// Now, add models to the collection.
Cows.add({
name: 'Bessie',
hasSpots: true
});
Cows.add({
name: 'Frank',
hasSpots: false
});
现在这是诀窍。我只想要牧场上有斑点的奶牛。在定义我的 CollectionView (Pasture) 时,我如何告诉它只关注那些hasSpots
===的模型true
?
理想情况下,我希望在所有事件中都有 CollectionView 过滤器,但至少,我如何只根据它们的模型属性渲染一些 ItemView?
更新
我使用了 David Sulc 的示例,这是一个简单的解决方案。这是一个示例实现:
this.collection = Backbone.filterCollection(this.collection, function(criterion){
var len = String(criterion).length;
var a = criterion.toLowerCase();
return function(model){
var b = String(model.get('name')).substr(0, len).toLowerCase();
if (a === b) {
return model;
}
};
});
this.collection.add({ name: 'foo' });
this.collection.add({ name: 'foosball' });
this.collection.add({ name: 'foo bar' });
this.collection.add({ name: 'goats' });
this.collection.add({ name: 'cows' });
this.collection.filter('foo');
// -> returns the first three models