简体   繁体   English

Backbone.js集合有多种排序

[英]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. 谢谢。

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")]
}

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. 其中sortBy返回一个新的,已排序的数组,该数组作为参数传递给reset。 SortingField is the string property of the model. SortingField是模型的字符串属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM