Search code examples
javascriptbackbone.jsbackbone-viewsbackbone.js-collections

Filtering a Collection With Backbone MV*


I have a collection of transactions that have amount, description, type(debit/credit) and categories (home, auto, misc, etc). I'm trying to filter out my results to show only 'home' category in this example. I have my other view working to display all results from my collection. Below I tried to create a new collection 'results' and then output this to my handlebars template.

render: function () {
    var results = this.collection.where({category: "home"});
    var filteredCollectionHome = new Backbone.Collection(results);

    this.$el.html(this.template({filteredCollectionHome: this.collection.homeView(true)}));
}

The homeView is inside my collections file.

homeView: function (toJSON) {
        this.sortByDate(-1); // descending so latest are first

        if(!toJSON) {
            return this.models;
        } else {
            var models = this.models,
                idx = -1,
                json = [],
                model;

            while(model = models[++idx]) {
                json.push(model.attributes);
            }
            return json;
        }   

    },

Solution

  • Add a method in your collection which filters the data you want and return a new collection with filtered results.

    var Transactions = Backbone.Collection.extend({
      model: Transaction,
    
      byCategory: function(name) {
        filtered = this.filter(function(trans) {
          return trans.get("category") === name;
          });
        return new Transactions(filtered);
      }
    
    });
    
    var home_transactions = Transactions.byCategory("home")