I am refactoring my Backbone.js application to use Marionette.js, and I am trying to wrap my head around a CollectionView
.
Suppose I have several ItemView
s with the model 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
});
Now here's the trick. I only want cows with spots in my pasture. How, in defining my CollectionView (Pasture), do I tell it to only pay attention to those models whose hasSpots
=== true
?
Ideally I would like to have the CollectionView filter that in all events, but minimally, how do I only render some ItemViews based on their model properties?
UPDATE
I used David Sulc's examples and this worked out to an easy solution. Here's an example implementation:
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