Filter backbone collection by attribute value

前端 未结 2 2067
一向
一向 2020-12-12 19:03

I have a defined model and a collection:

var Box = Backbone.Model.extend({
    defaults: {
        x: 0,
        y: 0,
        w: 1,
        h: 1,
        co         


        
2条回答
  •  萌比男神i
    2020-12-12 19:54

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

提交回复
热议问题