Skip to content Skip to sidebar Skip to footer

Sorting Backbone Collections

The desired functionality I'm using a Backbone.Collection to view data in a sortable list. I've got the part down where clicking on certain dom elements sets properties on my Colle

Solution 1:

The comparator() function is called in the scope of the collection by default, at least in the most current version of Backbone.

I suspect that you may have broken that by defining the sortBy() function. That function is already defined by Backbone, and is used internally by Backbone's sort() function in some cases. Try removing that function and see if it works as expected.

It appears that you're just using sortBy() to reverse the order of your sort. That can be accomplished in the comparator() function by multiplying your return value by -1 when appropriate.

Solution 2:

As per the other answer, modify you sortBy method to call the original Collection.sortBy method like this:

sortBy: function(){
  var models = Backbone.Collection.prototype.sortBy.apply(this, arguments);
  if (this.sortOrder != 'asc') {
    models.reverse();
  }
  return models;
}

Post a Comment for "Sorting Backbone Collections"