I am redesigning the Backbone.js application to use Marionette.js and I am trying to wrap my head around CollectionView .
Suppose I have several ItemView with a Cow model:
// 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 is the trick. I want only cows with spots on my pasture. How, when defining my CollectionView (Pasture), I say that it only draws attention to those models whose hasSpots === true ?
Ideally, I would like to have a CollectionView filter, which in all cases, but minimally, how do I display only some ItemViews based on their model properties?
UPDATE
I used David Sulc examples and it worked for a simple solution. Here is 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');
source share