Recently I had a need to sort a list of records in a list by the Date it was created and I wanted to do so using backbone, well it turns out there is a very simple and slick way to get this done, I have included the code snippets below:
The collection:
04 | ], function (backbone, model) { |
05 | return backbone.Collection.extend({ |
09 | comparator: function (item) { |
10 | return -item.get( this .sort_key); |
12 | sortByField: function (fieldName) { |
13 | this .sort_key = fieldName; |
As you can see you just use the comparator: function built into the backbone collections and in my example I am passing a negative so that it will sort descending, the default is ascending so just leave the minus sign off if you want it to work that way. I included the sortByField function here as a convenient way to call it in the code off the collection, it uses the sort_key field in the comparator to organize your collection. Below I have the usage, as you can see, its just a simple call to the string name of the field you want to sort by.
The usage:
1 | new collection().fetch({ |
2 | data: { data: "whatever" }, |
3 | success: function (r) { |
4 | r.sortByField( "FieldToSortBy" ); |
6 | error: function (c, r) { |
7 | alert( "Error retrieving the data." ); |