2012-07-16 49 views
11

我有一個表格中呈現的骨幹集合。我想根據集合具有的某些屬性將表格排序,如「task_status」,「task_group」。我正在閱讀有關collection.comparator,nd collection.sort的主幹文檔。 我該怎麼做到這一點?基於模型屬性的排序骨幹集合

回答

29

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; 
}  

,然後你只需要在收集一些方法來改變sort_key,並呼籲sort

sort_by_thing: function() { 
    this.sort_key = 'thing'; 
    this.sort(); 
} 

在較老的骨幹網中,呼叫sort將觸發"reset"事件,而較新的版本將觸發"sort"事件。爲了彌補這兩種情況下,你可以聽的事件和重新渲染:

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

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

您還可以使用listenTo代替on來幫助你避免殭屍:

initialize: function() { 
    this.listenTo(this.collection, 'reset sort', this.render); 
} 

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

+0

我可以在一個情況下的排序字段是字符串 – MrFoh 2012-07-16 19:28:36

+0

@MrFoh使用這種模式在字符串中,演示中的's'屬性是一個字符串。 – 2012-07-16 20:16:34

+1

請注意,此示例不再有效,因爲Backbone不再在排序時觸發重置事件。它觸發排序事件。 – 2013-06-19 23:15:58

20

@ 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(); 
    } 
}); 

在這之後你可以調用集合的sortByField - 函數與表示要排序的鍵的字符串。 例如:

collection.sortByField('name'); 

修改@我,是太短的演示:http://jsfiddle.net/NTez2/39/

+1

請注意,此示例不再有效,因爲Backbone不再在排序時觸發重置事件。它觸發排序事件。 – 2013-06-19 23:21:34

+1

感謝您的領導!我更新了該示例以適應該更改:http://jsfiddle.net/NTez2/39/ – jylauril 2013-06-25 11:31:37

+1

單參數比較器(和'_.sortBy')的大問題是無法在升序和降序之間切換以任何理智的方式處理字符串。數字降序很容易,因爲您可以取消數字,但否定字符串並不容易。如果不將它們混合到一個單獨的字符串中,您也無法按幾個鍵進行排序,並且需要注意將其正確設置。 – 2013-08-15 16:15:07

3

@ jylauril的回答有極大的幫助,但是需要修改演示(在骨幹網或許細微變化,因爲它被張貼?)

看起來您需要在排序後觸發渲染。

$('#by-s').click(function() { 
    c.sortByField('s'); 
    v.render(); 
}); 

更新@我,是太短的演示:是的,'>`和`<`工作:http://jsfiddle.net/NTez2/13/