Filter backbone collection by attribute value

前端 未结 2 2052
一向
一向 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条回答
  • 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")
    
    0 讨论(0)
  • 2020-12-12 20:07

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

    var red_boxes = boxes.where({color: "red"});
    
    var red_collection = new Boxes(red_boxes);
    
    0 讨论(0)
提交回复
热议问题