Backbone collection sorting.

May 14th, 2013 by admin Leave a reply »

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:

01define([
02  'backbone',
03  'Models/YourModel'
04], function (backbone, model) {
05    return backbone.Collection.extend({
06        url: '/your_url/',
07        model: model,
08        sort_key: 'id', // default sort key
09        comparator: function (item) {
10            return -item.get(this.sort_key);
11        },
12        sortByField: function (fieldName) {
13            this.sort_key = fieldName;
14            this.sort();
15        }
16    });
17});

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:

1new collection().fetch({
2                data: { data: "whatever" },
3                success: function (r) {
4                        r.sortByField("FieldToSortBy");
5                },
6                error: function (c, r) {
7                    alert("Error retrieving the data.");
8                },
9            });

Advertisement

Leave a Reply