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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With