Backbone.js: correct way of filtering a collection?

后端 未结 2 1953
时光取名叫无心
时光取名叫无心 2021-01-12 04:30

The current method I\'m using is to filter a collection, which returns an array, and use

collection.reset(array)

to re-populate it. However

2条回答
  •  庸人自扰
    2021-01-12 05:06

    You could create a collection as a property of the main collection reflecting the state of the filters:

    var C = Backbone.Collection.extend({
        initialize: function (models) {
            this.filtered = new Backbone.Collection(models);
            this.on('add', this.refilter);
            this.on('remove', this.refilter);
        },
    
        filterBy: function (params){
            var filteredColl = this.filter(function(item){
              // ...
            });
    
            this.filtered.params = params;
            this.filtered.reset(filteredColl);
        },
    
        refilter: function() {
            this.filterBy(this.filtered.params);
        }
    });
    

    The parent collection keeps its models whatever filters you applied, and you bind to the filtered collection to know when a change has occurred. Binding internally on the add and remove events lets you reapply the filter. See http://jsfiddle.net/dQr7X/ for a demo.

提交回复
热议问题