Search⌘ K

Creating a New File for Collection

Explore how to create and implement a FilteredCollection in Marionette.js. Understand how to manage an original collection and apply both custom and built-in filtering methods to refine data views. This lesson helps you encapsulate filtering logic, enabling flexible data handling and chaining of filter calls in Backbone collections.

Let’s create a FilteredCollection object in our Entities module based on Derick Bailey’s code. Its role will be to manage and encapsulate the collection filtering we used in the “Filtering Contacts” chapter. When we instantiate a filtered collection, we’ll need to provide the base collection (containing all the models), as well as a filtering function, like this:

Node.js
var filteredContacts = new ContactManager.Entities.FilteredCollection({
collection: contacts,
filterFunction: function(filterCriterion){
return function(contact){
if(contact.get("firstName") === filterCriterion){
return contact;
}
};
}
});

Steps to create a FilteredCollection

We need to follow the steps below to create our FilteredCollection:

Flowchart for creating a FilteredCollection
Flowchart for creating a FilteredCollection

Let’s start by adding basic creation code to a new file:

Node.js
ContactManager.module("Entities", function(Entities, ContactManager,
Backbone, Marionette, $, _){
Entities.FilteredCollection = function(options){
var original = options.collection;
var filtered = new original.constructor();
filtered.add(original.models);
filtered.filterFunction = options.filterFunction;
return filtered;
};
});

Explanation

  • Line 4: We store a reference to the original collection (containing all of the ...