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 hidden or 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; | |
}; | |
} |
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
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.
For additional help on
localeCompare
check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare