Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js collection with multiple sorts

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.

like image 460
chenglou Avatar asked Aug 08 '12 18:08

chenglou


2 Answers

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.

like image 161
user2272430 Avatar answered Oct 03 '22 03:10

user2272430


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")]
}
like image 31
Mason Zhang Avatar answered Oct 03 '22 03:10

Mason Zhang