From cea2f3fb86716dbae96a3e2a2d15c310ad2ac198 Mon Sep 17 00:00:00 2001 From: Ferran Basora Date: Wed, 9 Apr 2014 09:45:17 +0200 Subject: [PATCH] Added reverse option in the collection sort method 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. --- backbone.js | 4 ++++ test/collection.js | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/backbone.js b/backbone.js index d99ef32b8..b1b0bdc36 100644 --- a/backbone.js +++ b/backbone.js @@ -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; }, diff --git a/test/collection.js b/test/collection.js index 47a9f15a6..8062c22ac 100644 --- a/test/collection.js +++ b/test/collection.js @@ -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) {