Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort backbone collection based on model attributes

I have a backbone collection which is rendered in a table. I would like to make the table sortable based on certain attributes the collection has, like "task_status","task_group". I've being reading the backbone documentation about collection.comparator,nd collection.sort. How can I get this done?

like image 718
MrFoh Avatar asked Jul 16 '12 18:07

MrFoh


1 Answers

The comparator function is used to compare two models in the collection and it can compare them in any (consistent) way that it wants to. In particular, it can choose which model attribute to use so you could have something like this in your collection:

initialize: function() {
    this.sort_key = 'id';
},
comparator: function(a, b) {
    // Assuming that the sort_key values can be compared with '>' and '<',
    // modifying this to account for extra processing on the sort_key model
    // attributes is fairly straight forward.
    a = a.get(this.sort_key);
    b = b.get(this.sort_key);
    return a > b ?  1
         : a < b ? -1
         :          0;
}    

and then you just need some methods on the collection to change the sort_key and call sort:

sort_by_thing: function() {
    this.sort_key = 'thing';
    this.sort();
}

In older Backbones, calling sort will trigger a "reset" event whereas newer versions will trigger a "sort" event. To cover both cases you can listen to both events and re-render:

// in the view...
initialize: function() {
    this.collection.on('reset sort', this.render, this);
}

Demo: http://jsfiddle.net/ambiguous/7y9CC/

You can also use listenTo instead of on to help you avoid zombies:

initialize: function() {
    this.listenTo(this.collection, 'reset sort', this.render);
}

Demo: http://jsfiddle.net/ambiguous/nG6EJ/

like image 127
mu is too short Avatar answered Sep 28 '22 03:09

mu is too short