Backbone.js: correct way of filtering a collection?

后端 未结 2 1864
时光取名叫无心
时光取名叫无心 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 04:50

    The major problem on your code is that you are using a raw array as original, instead of a Collection. My code is close to the yours but use only Collections, so methods like add, remove and filter works on the original:

      var OriginalCollection = Backbone.Collection.extend({
      });
      var FilteredCollection = Backbone.Collection.extend({
        initialize: function(originalCol){
            this.originalCol = originalCol;
            this.on('add', this.addInOriginal, this);
            this.on('remove', this.removeInOriginal, this);
        },
        addInOriginal: function(model){
            this.originalCol.add(model);
        },
        removeInOriginal: function(model){
            this.originalCol.remove(model);
        },
        filterBy: function(params){
            var filteredColl = this.originalCol.filter(function(item){
                // filter code...
            });
            this.reset(filteredColl);
        }   
      });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题