按属性值过滤主干集合 [英] Filter backbone collection by attribute value

查看:24
本文介绍了按属性值过滤主干集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

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

推荐答案

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

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

这篇关于按属性值过滤主干集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆