Marionette.js Collectionview, Only Render Specific Models
Solution 1:
Marionette handles this for you in v2.4.1.
See the CollectionView.filter method.
Following is from the docs:
var cv = newMarionette.CollectionView({
childView: SomeChildView,
emptyView: SomeEmptyView,
collection: newBackbone.Collection([
{ value: 1 },
{ value: 2 },
{ value: 3 },
{ value: 4 }
]),
// Only show views with even valuesfilter: function (child, index, collection) {
return child.get('value') % 2 === 0;
}
});
// renders the views with values '2' and '4'
cv.render();
// change the filter
cv.filter = function (child, index, collection) {
return child.get('value') % 2 !== 0;
};
// renders the views with values '1' and '3'
cv.render();
// remove the filter// note that using `delete cv.filter` will cause the prototype's filter to be used// which may be undesirable
cv.filter = null;
// renders all views
cv.render();
Solution 2:
As suggested by others, the best way to achieve this is to filter the collection to contain only the models you want to display, and pass that fitlered collection to a CollectionView for rendering.
You can see a working example here: http://davidsulc.github.io/marionette-gentle-introduction/#contacts Filter contacts with the input field on the top right to display only models containing that text (e.g. "li").
This is achieved by using a special collection type that handles filtering: https://github.com/davidsulc/marionette-gentle-introduction/blob/master/assets/js/entities/common.js
And it gets instantiated here: https://github.com/davidsulc/marionette-gentle-introduction/blob/master/assets/js/apps/contacts/list/list_controller.js#L13
This code is from my book on Marionette.
Solution 3:
@Will M's suggestion to filter the collection is the appropriate way to do this.
Solution 4:
Sometimes you can not filter your collection due to some custom logic and you want those models to be in a collection, but you don't want them to be rendered. To achieve it, you can:
varPasture = Marionette.CollectionView.extend({
addChild: function(child, ChildView, index) {
if(child.get('hasSpots')) {
returnMarionette.CollectionView.prototype.addChild.call(this, child, ChildView, index);
}
}});
Although I agree that filtering a collection is a much better way to do this.
Post a Comment for "Marionette.js Collectionview, Only Render Specific Models"