2012-08-01 45 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