2013-08-01 72 views
2

我有一個主幹和下劃線的應用程序。 我已經看到了這個問題,但我haven'0t解決我的問題,因爲是不同的一點:
Sorting Backbone Collections
Backbone/Underscore sortBy is not sorting collection骨幹排序收集數組

我的問題是:我有一個集合到一個視圖,我想對它進行排序字段順序以及將此集合打印到模板中之後。

我都試過,但不以下劃線工作:

this.hotels.models = _(this.hotels.models).sortBy("order"); 
$(this.el).html(this.template({hotels: this.hotels.models})); 

我如何排序我的收藏(模型),打印後inot模板? 我的代碼不排序我的數組。

回答

6

models數組是模型對象的數組,其屬性存儲在model.attributes中。包裝數組並調用sortBy假定被排序的對象是普通對象,並且該屬性可直接作爲model.{attribute}訪問。

爲了得到它做你想做的,你可以通過sortBy比較功能是什麼get是你想要的屬性:

this.hotels.models = _(this.hotels.models).sortBy(function(model) { 
    return model.get("order"); 
}); 

但是這是骨幹已經做的集合類。要使用內置比較器,只需將Collection的comparator屬性設置爲要排序的Model屬性的名稱即可。

例子:

this.hotels.comparator = "order"; 
this.hotels.sort(); 
$(this.el).html(this.template({hotels: this.hotels.models})); 
+1

由於該解決的問題,並誠懇我不明白怎麼用比較...嗯,你可以做一個簡單的例子嗎? +1的答案 –

+1

我更新了我的答案,更多的解釋'比較器' – freejosh

+0

非常感謝!這是我想要的! –