Backbone Collection Decorators

filtering, sorting and other decorators are easy to do with backbone collections.

by derickbailey

HTML

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<label>filter: <input id="filter"></label>
<div id="output"></div>
<p>&nbsp;</p>
<p>
    Type in to the text box. enter one of the items: "bar", "baz", "quux" and then tab out of the text box. It will filter to show only the items with that name. Empty the filter input and tab out again, to see the full list.
</p>

JavaScript

function FilteredCollection(original){
    var filtered = Object.create(original);

    filtered.filter = function(criteria){
        var items;
        if (criteria){
            items = original.where(criteria);
        } else {
            items = original.models;
        }
        filtered.reset(items);
    };        
    
    return filtered;
}
    
var stuff = new Backbone.Collection();

var filtered = FilteredCollection(stuff);
var view = Backbone.View.extend({
    initialize: function(){
        this.collection.on("reset", this.render, this);
    },
    
    render: function(){
        var result = this.collection.map(function(item){ return item.get("foo"); });
        this.$el.html(result.join(","));
    }
});

    
new view({
    el: $("#output"),
    collection: filtered
});


$("#filter").change(function(e){
    var val = $(e.currentTarget).val();
    if (val){
        filtered.filter({foo: val});
    } else {
        filtered.filter();
    }
});


stuff.reset([
    {foo: "bar"},
    {foo: "baz"},
    {foo: "quux"},   
    {foo: "bar"},
    {foo: "baz"},
    {foo: "quux"}   
]);


filtered.filter();