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:
define([ 'backbone', 'Models/YourModel' ], function (backbone, model) { return backbone.Collection.extend({ url: '/your_url/', model: model, sort_key: 'id', // default sort key comparator: function (item) { return -item.get(this.sort_key); }, sortByField: function (fieldName) { this.sort_key = fieldName; this.sort(); } }); });
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:
new collection().fetch({ data: { data: "whatever" }, success: function (r) { r.sortByField("FieldToSortBy"); }, error: function (c, r) { alert("Error retrieving the data."); }, });