Share this blog!

Filtering models in a Backbone collection

This example shows how to use Backbone's filter method to apply a filter on a Backbone's collection based on a condition.

Define a model and collection

First let's define a simple model for a book.

 var Book = Backbone.Model.extend({
                title: "title",
                author: "author",
                subject: "subject" 
            }); 

Now let's define a collection called library.
 var Library = Backbone.Collection.extend({
                model: Book,
                url: "/connectors" 
            }); 

Filter it out

It's time to define a filter method. Imagine you wish to filter books by the author. The magic lies in the following teeny tiny piece of code.

this.filter(d => d.get('author') === "myAuthor")


Note that the arrow functions use ECMAScript 6, which might not be recognizable by certain IDE's. A really good post on using arrow functions in in the related links at the end of the page. Keep scrolling!

Once this filter is added to our collection as a function, the collection will look like this.

 var Library = Backbone.Collection.extend({
                model: Book,
                url: "/connectors",
                filterByAuthor: function (author) {
                    return this.filter(d => d.get('author') === author);
                }
            }); 


Forget the arrows

An alternative to the arrow functions will be calling as a usual JS function.

 var Library = Backbone.Collection.extend({
                model: Book,
                url: "/connectors",
                filterByAuthor: function(author) {  
                     return this.filter(function(d) {
                          return d.get('author') === author;
                     });
                }
            }); 


Done and dusted

The result of the above will be an array of models that obeys the condition specified in the filter. You can easily loop through the items using Javascript's map function.

 library.filterByAuthor().map(function (book) { //iterate through the array of books  
                    book.printDetails();
                }); 


The working code

The working JSFiddle, with a teeny bit more sophisticated code, is shown below:


  1. A post on arrow functions in ES6.
Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment