Search code examples
javascriptsortingbackbone.js

Sorting backbone collection on three model attributes


I looked into http://backbonejs.org/#Collection-comparator and for one model attribute, as shown in the example, the sorting working just fine. However, I want to sort on multiple attributes and the following post suggested that this could be done for more than one attribute:

Backbone.js collection comparator sort by multiple fields?

comparator: function(item) {
  return [item.get("level"), item.get("title")]
}

I am able to sort on two attributes as suggested in the example above, however, if I add one additional attribute (a 3rd attribute), the sorting doesn't work on that third attribute.

Can someone explain why this works for one and two attributes, but not for three?

Below is how I define the comparator:

var aCollection = Backbone.Collection.extend({
    model: Model,
    comparator: function(item){
      return [item.get('uid'), item.get('vid'), item.get('wid')];
    },
    ...
});

Solution

  • Just to be clear, I am using require.js with backbone. To solve this problem, I did a ton of Googling an then tried the following, which worked. When loading up my collection, I have created a comparator function that takes in two arguments. Example: jsfiddle

    comparator: function(a, b){
    
    var fields = ['uid','vid','wid'],
                directions = ['asc', 'asc', 'asc'],
                cmpOn;
    
            cmpOn = _.find(fields, function(c){
               return a.attributes[c] != b.attributes[c];
            });
    
            if(!cmpOn) return 0;
    
            if ( ( directions[_.indexOf( fields, cmpOn )] || 'asc' ).toLowerCase() == 'asc' ) {
                return a.attributes[cmpOn] > b.attributes[cmpOn] ? 1 : -1;
            } else {
                return a.attributes[cmpOn] < b.attributes[cmpOn] ? 1 : -1;
            }
    
    }