Filter and sort backbone collection with array of

2019-02-18 04:05发布

问题:

I'm quite new to Backbone so I am getting into some problems I can't quite figure out.

I have a Backbone collection with a bit over 100 items. I want to filter these with an array of ids, that is working fine, but I want the order of the items also based on this array's order of items. That is not working. The other sorting methods seems to be asciibetical based, that's not what I need either. Is it possible to get items using this filter, and then also put them into the collection in the order I've defined?

I have an array of id's that I filter with, this array looks like this:

var dDefaultItems = ['1','2','146','3','4','9','26','8','96','10','11','54','145','273','38'];

The code for the collection and filtering looks like this:

var ChannelCollection = Backbone.Collection.extend({        
    fetch : function() {
       var params = _.extend({}, arguments, { 
            data : { 
                "groupnumber" : "1000"
            }
        });
        this.constructor.__super__.fetch.apply(this, [params]);

    },

    model : Channel,

    url : function () {
        return utility.apiUrl('/myurl/tothething');  
    },

    filterData: function(params) {

        this.originalModels = this.models.slice();

        _.each(params, function(val, key){
            if (typeof val !== 'object') val = [ val ];
            this.models = _.filter(this.models, function(model){
                return _.indexOf(val, model.get(key)) !== -1;
            }, this);
        }, this);
        return this.reset(this.models).toJSON();
    },

    parse : function(json) {            

        return json.channelInfoList;
    }

 });

Then I render this in a view with this code (there's other bits of code for defining model and other attributes that I don't think is relevant, I may be wrong, but I'm thinking someone will know what I need from looking at this.)

var ChannelListView = Backbone.View.extend({

    initialize: function() {
       var _this = this;

        currentChannelList = new ChannelCollection();

        currentChannelList.once("sync", function() {
           _this.render();
        });

        currentChannelList.fetch();
    },
    render : function() {
      var _this = this;

      $(_this.el).empty();

     dust.render("list-channels", { channelList : currentChannelList.filterData({id: dDefaultItems})} , function(err, html) {

        var $el = $(html).appendTo($(_this.el));
      });  
    }
 });   

回答1:

Backbone collections are automatically sorted by the order of insertion, unless you implement Collection#comparator. The problem is that your filtering algorithm is not producing an ordered output.

If you need to maintain an ordered collection only when filtering by id, I would suggest implementing a separate method, because seach by id is far faster compared to search by arbitrary attributes:

filterById: function(idArray) {
  return this.reset(_.map(idArray, function(id) { return this.get(id); }, this));  
}

Usage:

collection.filterById(['1', '2', '146', '3', '4', '9', '26', '8', '96', '10', '11', '54',' 145', '273', '38']);