Filter backbone collection by attribute value

I like returning a new instance of the collection. This makes these filtering methods chainable (boxes.byColor("red").bySize("L"), for example).

var Boxes = Backbone.Collection.extend({
    model: Box,

    byColor: function (color) {
        filtered = this.filter(function (box) {
            return box.get("color") === color;
        });
        return new Boxes(filtered);
    }
});

var red_boxes = boxes.byColor("red")

Leave a Comment