Backbone.js collection with multiple sorts

I have a to-do list with a name and a date. I would like to be able to sort the list using either the name or the date. How should I do it? The comparator allows only one type of sorting.

Thank.

+5
source share
3 answers

I think I found a method:

collection.reset(collection.sortBy(function(item){
    return item.get(sortingFIeld);
}))

Where sortBy returns a new, sorted array that is passed as a reset argument. SortingField is a string property of the model.

+1
source

You can implement more logic in the comparator so that you can abstract away from some 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 the sort order:

myCollection.order = 'date';
myCollection.sort();

This will call the comparator function and sort it that way.

:

this.listenTo(myCollection,'sort',this.render);

, , , , .

+4

You may need to answer here , here is the solution provided in this post:

comparator: function(item) {
    return [item.get("level"), item.get("title")]
}
+3
source

All Articles