53

I am using Backbone.js to render a list of items e.g Books. After the list is rendered, there are options for user to sort them. So if user clicks on Sort By Title, or Sort By Author Name the list will sort itself on the client side.

  window.Book = Backbone.Model.extend({
   defaults: {
     title: "This is the title",
     author: "Name here"
   },

What is the best way to accomplish this sort using in the context of a Backbone application. Do I use a jQuery dom sorter in the AppView?

Jhony Fung
  • 2,970
  • 4
  • 29
  • 32

4 Answers4

51

There's a discussion on this very topic that you might want to look at: https://github.com/documentcloud/backbone/issues/41.

The short of it is that when a user selects 'sort by X', you can:

  1. Set the comparator function on the Collection
  2. Call the Collection's sort function (which will trigger a sort event)
  3. Listen for the sort event in your View, and (clear and) redraw the items

Another way to handle steps 1 & 2 is to have your own method that calls the Collection's sortBy method and then triggers a custom event that your View can listen to.

But it seems to be the case that clearing and redrawing is the easiest (and maybe even the fastest) way to sort your View's and keep them in sync with your Collection's sort order.

Radko Dinev
  • 865
  • 7
  • 15
satchmorun
  • 12,487
  • 2
  • 41
  • 27
  • Thanks rulfzid. I am going to try this approach out – Jhony Fung Aug 10 '11 at 19:03
  • 8
    Correction for 2. the `sort` event is the one that gets fired when the Collection's sort function is called, not `reset` – CheapSteaks Mar 12 '13 at 19:50
  • In your view you need to listen to the 'sort' event not 'reset' (I think that's older versions of backbone). Pass the same collection to the view and use: this.listenTo(this.collection, 'sort', this.render); – Fasani Aug 14 '13 at 20:50
  • Will that create a ton of zombie views? It seems that every time you "sort" you are creating new Backbone view objects which takes additional time and space and leaving old view objects hanging around. – benjaminz Sep 23 '15 at 14:48
51

You can update the comparator function and then call the sort method.

// update comparator function
collection.comparator = function(model) {
    return model.get('name');
}

// call the sort method
collection.sort();

The view will be automatically re-rendered.

Kemal Dağ
  • 2,743
  • 21
  • 27
jpanganiban
  • 1,089
  • 10
  • 9
12

comparator is what you need

var PhotoCollection = Backbone.Collection.extend({
    model: Photo,
    comparator: function(item) {
        return item.get('pid');
    }
});
Nick Vanderbilt
  • 1,757
  • 2
  • 17
  • 22
  • 2
    Isn't comparator used for sorting the collection during initialization. After the list has been displayed, the user have actions to re-sort them in different ways and that's what I need to figure out. – Jhony Fung Aug 10 '11 at 13:10
4

This way works well and enables sorting by all attributes dynamically and handles ascending or descending:

var PhotoCollection = Backbone.Collection.extend({
    model: Photo,
    sortByField: function(field, direction){
            sorted = _.sortBy(this.models, function(model){
                return model.get(field);
            });

            if(direction === 'descending'){
                sorted = sorted.reverse()
            }

            this.models = sorted;
    }
});
Loourr
  • 4,995
  • 10
  • 44
  • 68