I have a todo list with name and date. I'd like to be able to sort the list using either the title or to the date. How would I do this? Comparator allows only one type of sorting.
Thanks.
It is possible to implement more logic into the comparator so that you can abstract away some of the sorting logic:
var Collection = Backbone.Collection.extend({
model: myModel,
order: 'name'
comparator: function(model) {
if (this.order === 'name') {
return model.get('name');
} else {
return model.get('date'); //or modify date into a numeric value
}
}
});
Then to change how you want it sorted:
myCollection.order = 'date';
myCollection.sort();
This will call the comparator function and sort it this way.
You can listen for the resorting in a view:
this.listenTo(myCollection,'sort',this.render);
This has the added advantage that every time a model is added, it calls the comparator and sorts it using whatever your current setting is, because the sorting method is stored in the collection.
You may need to look at the answer here, here is the solution provided in that post:
comparator: function(item) {
return [item.get("level"), item.get("title")]
}
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