按属性值过滤主干集合

rpa*_*bon 42 backbone.js underscore.js backbone.js-collections

我有一个已定义的模型和一个集合:

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

});

var Boxes = Backbone.Collection.extend({
    model: Box
});
Run Code Online (Sandbox Code Playgroud)

当使用模型填充集合时,我需要一个由Box模型制作的新Boxes集合,这些集合具有完整集合中包含的特定颜色属性,我这样做:

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);
Run Code Online (Sandbox Code Playgroud)

这有效,但我发现它有点复杂和低效.有没有办法以更简单的方式做同样的事情?

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

hgm*_*mnz 83

我喜欢返回集合的新实例.这使得这些过滤方法可链接(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")
Run Code Online (Sandbox Code Playgroud)

  • Marcoslhc:这不会返回Backbone集合,而是返回一系列模型 (5认同)
  • filterBy:function(attribute,value){filtered = this.filter(function(box){return box.get(attribute)=== value;}); 返回新框(已过滤); } (4认同)
  • 这会改变模型中的cid吗? (3认同)
  • 你可能想在其范围内声明`filtered`变量(`byColor`函数) (3认同)
  • 这是使用来自Underscore.js的过滤器吗? (2认同)

And*_*rei 46

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

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

var red_collection = new Boxes(red_boxes);
Run Code Online (Sandbox Code Playgroud)

  • `where`返回集合的数组,而不是集合对象. (8认同)