2013-08-01 70 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

非常感谢!这是我想要的! –