骨干排序集合数组

时间:2013-08-01 14:22:12

标签: backbone.js underscore.js

我有一个主干和下划线的应用程序。 我已经看过这个问题,但我没有解决我的问题,因为有点不同:
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}));

如何对我的集合(模型)进行排序并在打印后输入模板? 我的代码没有对我的数组进行排序。

1 个答案:

答案 0 :(得分:7)

models数组是一个Model对象数组,其属性存储在model.attributes中。包装数组并调用sortBy假定正在排序的对象是普通对象,并且该属性可以直接访问为model.{attribute}

为了让它做你想做的事,你可以传递sortBy比较器函数get你想要的属性:

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

然而,这就是Backbone在Collection类中已经做过的事情。要使用内置比较器,只需将Collection的comparator属性设置为要对其进行排序的Model属性的名称。

示例:

this.hotels.comparator = "order";
this.hotels.sort();
$(this.el).html(this.template({hotels: this.hotels.models}));
相关问题