Ember PromiseArray sortBy

时间:2014-02-27 19:14:52

标签: javascript ember.js ember-data handlebars.js

好的,所以我有一个控制器,其模型设置如下:

App.MyModel = DS.Model.extend({
    myOtherProperty: attr(),
    mySortKey: attr(),
    mySubCollection: function () {
        return this.store.filter('MyOtherModel', function (myOtherModel) {
            //Some basic filtering logic (it's actually more complex than this)
            return myOtherModel.get('someProperty') == this.get('myOtherProperty');
        });
    }.property('myOtherProperty')
})

实际的过滤功能并不重要 - 重要的是'mySubCollection'计算属性返回DS.PromiseArray对象。上述模型的控制器类型为'Ember.ObjectController',因为它只显示单个对象。

显示此属性的模板使用{{each}}帮助程序执行此操作:

MyTemplate的:

{{#each mySubCollection}}
    {{view App.MyView}}
{{/each}}

现在 - 我需要按'mySortKey'属性按降序对此promise数组进行排序。我怎样才能做到这一点?文档说DS.PromiseArray从Ember.Array扩展,但在'mySubCollection'的计算属性末尾添加'sortBy('mySortKey:desc')'导致它破坏而根本不起作用 - 这是有道理的,因为我会在承诺而不是数组上调用'sortBy'。

我已经看了很多不同的想法,并且不断出现的想法是切换到使用ArrayController。我可以做到这一点,但它并不理想,因为它在一个非常简单的设置之上增加了一堆复杂性,它已经很好用了(除了排序)。

有什么想法吗?

2 个答案:

答案 0 :(得分:9)

我无法弄清楚为什么sortBy无效PromiseArray。但这是我用作解决方法的方法:

sortedCollection: function() {
    return Em.ArrayProxy.createWithMixins(Em.SortableMixin, {
        content: this.get('mySubCollection'),
        sortProperties: [this.get('mySortKey')],
        sortAscending: false
    });
}.property('mySubCollection', 'mySortKey')

答案 1 :(得分:4)

Ember.SortableMixin已被弃用,请改用Ember.computed.sort

App.MyModel = DS.Model.extend({
    myOtherProperty: attr(),
    mySortKey: attr(),
    mySubCollection: ...
    sortedCollection: Ember.computed.sort('mySubCollection', function(a, b){
        # compare logic
        return a.get('time') - b.get('time');
    }
})