Skip to content

Commit

Permalink
Added reverse option in the collection sort method
Browse files Browse the repository at this point in the history
Added the reverse option to be able to sort the collection in the
inverse order specified by the comparator. Useful for one argument
comparators returning string values.

For boolean and integer comparators are easy to find the inverse
function to reverse the collection but for string comparators it's
not as easy as it seems.
  • Loading branch information
fcsonline committed Apr 9, 2014
1 parent c1710db commit cea2f3f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
4 changes: 4 additions & 0 deletions backbone.js
Original file line number Diff line number Diff line change
Expand Up @@ -870,6 +870,10 @@
this.models.sort(_.bind(this.comparator, this));
}

if (options.reverse) {
this.models = this.models.reverse();
}

if (!options.silent) this.trigger('sort', this, options);
return this;
},
Expand Down
22 changes: 22 additions & 0 deletions test/collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,28 @@
equal(col.indexOf(tom), 2);
});

test("reverse sort with a sortBy stylecomparator", function() {
var col = new Backbone.Collection;
col.comparator = function(a) {
return a.get('name');
};
var tom = new Backbone.Model({name: 'Tom'});
var rob = new Backbone.Model({name: 'Rob'});
var tim = new Backbone.Model({name: 'Tim'});
col.add(tom);
col.add(rob);
col.add(tim);

equal(col.indexOf(rob), 0);
equal(col.indexOf(tim), 1);
equal(col.indexOf(tom), 2);

col.sort({reverse: true});
equal(col.indexOf(tom), 0);
equal(col.indexOf(tim), 1);
equal(col.indexOf(rob), 2);
});

test("comparator that depends on `this`", 2, function() {
var col = new Backbone.Collection;
col.negative = function(num) {
Expand Down

0 comments on commit cea2f3f

Please sign in to comment.