admin管理员组

文章数量:1317131

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.

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.

Share Improve this question asked Aug 8, 2012 at 18:23 chenglouchenglou 3,6402 gold badges27 silver badges33 bronze badges 3
  • 1 Can I ask why you don't want to reset the collection ? There are reset triggers (for views) for this exact reason. i.e. when your sorting changes through a reset then your view re-renders. – Ashray Baruah Commented Aug 8, 2012 at 18:39
  • You're right, I see no disadvantage in resetting the whole collection. Thanks. – chenglou Commented Aug 8, 2012 at 18:44
  • It is normal to reset a collection when data changes, in your case the entire collection, even though it's the same data but in different order – Claudiu Hojda Commented Aug 8, 2012 at 18:50
Add a ment  | 

3 Answers 3

Reset to default 4

It is possible to implement more logic into the parator so that you can abstract away some of the sorting logic:

var Collection = Backbone.Collection.extend({

    model: myModel,
    order: 'name'

    parator: 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 parator 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 parator 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:

parator: function(item) {
    return [item.get("level"), item.get("title")]
}

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 argument to reset. SortingField is the string property of the model.

本文标签: javascriptBackbonejs collection with multiple sortsStack Overflow