2012-08-01 43 views
41

我有一个定义的模型和集合:筛选骨干集合根据属性值

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

}); 

var Boxes = Backbone.Collection.extend({ 
    model: Box 
}); 

当收集填充了款,我需要做的是有一个特定的彩色包装盒型号的新箱集属性包含完整的集合中,我做这种方式:

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); 

这工作,但我觉得有点复杂,效率不高。有没有办法以更简单的方式做同样的事情?

这里是我描述的代码:http://jsfiddle.net/HB88W/1/

回答

82

我喜欢返回集合的新实例。这使得这些过滤方法可链接(例如,boxes.byColor("red").bySize("L"))。

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") 
+3

将在模型中,这变化CID? – janetsmith 2013-03-11 13:30:21

+4

filterBy:函数(属性,值){ });函数(box){0} 返回新盒子(过滤); } – Josh 2013-07-07 15:27:20

+0

为什么要返回'new Boxes()'。我会写 VAR盒= Backbone.Collection.extend({ 型号:箱, byColor:功能(彩色){ 回报this.filter(函数(盒){ 回报box.get( “颜色”)= == color; }); } }); – marcoslhc 2013-10-09 20:03:02

43

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

var red_boxes = boxes.where({color: "red"}); 

var red_collection = new Boxes(red_boxes); 
+8

'where'返回集合的数组,而不是集合对象。 – seebiscuit 2014-05-08 19:56:24

+0

这是一个很好的解决方案,除非您被迫使用尚未实现“where”的旧版Backbone。 – paniclater 2014-05-23 19:39:33