Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter backbone collection by attribute value

I have a defined model and a collection:

var Box = Backbone.Model.extend({     defaults: {         x: 0,         y: 0,         w: 1,         h: 1,         color: "black"     }  });  var Boxes = Backbone.Collection.extend({     model: Box }); 

When the collection is populated with the models, I need a new Boxes collection made out of Box models that have a specific color attribute contained in the complete collection, I do it this way:

var sorted = boxes.groupBy(function(box) {     return box.get("color"); });   var red_boxes = _.first(_.values(_.pick(sorted, "red")));  var red_collection = new Boxes;  red_boxes.each(function(box){     red_collection.add(box); });  console.log(red_collection); 

This works, but I find it a bit complicated and unefficient. Is there a way of doing this same thing in a more simple way?

Here is the code I described: http://jsfiddle.net/HB88W/1/

like image 976
rpabon Avatar asked Aug 01 '12 15:08

rpabon


2 Answers

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") 
like image 138
hgmnz Avatar answered Nov 17 '22 01:11

hgmnz


See http://backbonejs.org/#Collection-where

var red_boxes = boxes.where({color: "red"});  var red_collection = new Boxes(red_boxes); 
like image 45
Andrei Avatar answered Nov 17 '22 00:11

Andrei