基于模型属性对骨干集合进行排序

MrF*_*Foh 13 javascript backbone.js

我有一个骨架集合,在表格中呈现.我想基于集合具有的某些属性使表可排序,例如"task_status","task_group".我正在阅读有关collection.comparator,nd collection.sort的主干文档.我怎么能这样做?

mu *_*ort 30

comparator函数用于比较集合中的两个模型,它可以以任何(一致)方式比较它们.特别是,它可以选择使用哪个模型属性,因此您可以在集合中使用以下内容:

initialize: function() {
    this.sort_key = 'id';
},
comparator: function(a, b) {
    // Assuming that the sort_key values can be compared with '>' and '<',
    // modifying this to account for extra processing on the sort_key model
    // attributes is fairly straight forward.
    a = a.get(this.sort_key);
    b = b.get(this.sort_key);
    return a > b ?  1
         : a < b ? -1
         :          0;
}    
Run Code Online (Sandbox Code Playgroud)

然后你只需要集合上的一些方法来改变sort_key和调用sort:

sort_by_thing: function() {
    this.sort_key = 'thing';
    this.sort();
}
Run Code Online (Sandbox Code Playgroud)

在较旧的Backbones中,调用sort将触发"reset"事件,而较新的版本将触发"sort"事件.要涵盖这两种情况,您可以收听这两个事件并重新渲染:

// in the view...
initialize: function() {
    this.collection.on('reset sort', this.render, this);
}
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/ambiguous/7y9CC/

您也可以使用listenTo而不是on帮助您避免僵尸:

initialize: function() {
    this.listenTo(this.collection, 'reset sort', this.render);
}
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/ambiguous/nG6EJ/


jyl*_*ril 21

@ mu-is-too-short的答案很好,除了有一种比较字段值更简单的方法:

基于字段对集合进行排序的最简单方法是提供比较器函数,该函数返回要排序的确切字段值.这种比较器导致Backbone调用sortBy函数,而不是sort它,然后它自己进行复杂的比较,你不必担心逻辑.

因此,实质上,您不必提供复杂的比较器功能,除非您有更高级的确定顺序的需求.

var myCollection = Backbone.Collection.extend({
    sort_key: 'id', // default sort key
    comparator: function(item) {
        return item.get(this.sort_key);
    },
    sortByField: function(fieldName) {
        this.sort_key = fieldName;
        this.sort();
    }
});
Run Code Online (Sandbox Code Playgroud)

在此之后,您可以sortByField使用表示要排序的键的字符串调用集合的-function.例如:

collection.sortByField('name');
Run Code Online (Sandbox Code Playgroud)

修改了@ my-is-too-short的演示:http://jsfiddle.net/NTez2/39/