Backbone.js: correct way of filtering a collection?

后端 未结 2 1970
时光取名叫无心
时光取名叫无心 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);
        }   
      });
    

提交回复
热议问题