Created
May 1, 2011 04:10
-
-
Save andrewdeandrade/950240 to your computer and use it in GitHub Desktop.
Reverse Alphabetical Sort in Backbone.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Assumption: You have a model with a name. | |
comparator: function (User) { | |
if (User.get("name")) { | |
var str = User.get("name"); | |
str = str.toLowerCase(); | |
str = str.split(""); | |
str = _.map(str, function(letter) { return String.fromCharCode(-(letter.charCodeAt(0))) }); | |
return str; | |
}; | |
} |
Really useful, thanks!
I was dealing with this too.
Backbone comparators can also take two arguments, which allows you to sort in reverse fairly easily with better performance.
Backbone.Collection.extend({
comparator: function(a, b) {
return -a.get('name').localeCompare(b.get('name'));
}
});
Edit: Actually, it's even easier using String#localeCompare.
How can i switch between asc and desc order in sorting collections
I know this is a little old @BastinRobin but if others stumble upon this, like I did, here's a little more code for clarity on the whole asc/desc bit.
Backbone.Collection.extend({
comparator: function(a, b) {
var direction = 1; // Asc
var direction = -1; // Desc
return direction * a.get('name').localeCompare(b.get('name'));
}
});
For additional help on localeCompare
check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare
My production example using @bryancallahan's suggestion:
// Presenter/Controller
function sortUsers() {
users.sortDirection = $usersView.hasClass('asc') ? -1 : 1; // dsc : asc
$usersView.toggleClass('asc')
users.sort();
}
// Collection
App.UserCollection = Backbone.Collection.extend({
comparator: function(a, b) {
return this.sortDirection * a.get('name').localeCompare(b.get('name'));
}
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Exactly what I needed, thanks!