Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

backbone.js - 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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...