Skip to content

Instantly share code, notes, and snippets.

@MattMcFarland
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattMcFarland/a77d6ac2310db729cf5f to your computer and use it in GitHub Desktop.
Save MattMcFarland/a77d6ac2310db729cf5f to your computer and use it in GitHub Desktop.
Backbone Comparator Snippet
// This hidden gem was found at http://stackoverflow.com/questions/9865804/proper-way-to-sort-a-backbone-js-collection-on-the-fly (buried in the answers)
// Following example above do in the view:
// Assign new comparator
this.collection.comparator = function( model ) {
return model.get( 'lastname' );
}
// Resort collection
this.collection.sort();
// Sort differently
this.collection.comparator = function( model ) {
return model.get( 'age' );
}
// Reverse Sort (Number only)
// Special thanks to http://stackoverflow.com/questions/5013819/reverse-sort-order-with-backbone-js
this.collection.comparator = function(model) {
return -model.get("age"); // Note the minus!
};
this.collection.sort();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment