【问题标题】:Backbone sort collection array骨干排序集合数组
【发布时间】:2013-08-01 14:22:11
【问题描述】:

我在主干和下划线中有一个应用程序。 我已经看到了这个问题,但我还没有解决我的问题,因为有点不同:
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 模板后? 我的代码没有对我的数组进行排序。

【问题讨论】:

    标签: backbone.js underscore.js


    【解决方案1】:

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

    要让它做你想做的事,你可以通过 sortBy 一个比较器函数 gets 你想要的属性:

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

    【讨论】:

    • 谢谢这解决了问题,而且我真的不明白如何使用比较器......嗯,你能举个简单的例子吗?为答案+1
    • 谢谢!清洁溶液。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    相关资源
    最近更新 更多