有没有办法在模板中使用sortProperties内联?

时间:2014-02-26 13:52:01

标签: ember.js

我创建了几个控制器和模板,如下所示,仅用于对属性进行排序。

例如:

App.ExamplesController = Ember.ArrayController({
  sortProperties: ['index']
});

模板('examples'):

{{#each}}
  {{foo}}
{{/each}}    

模板('app'):

<h1>MyApp</h1>
{{render 'examples' offers}}

是否有一种不那么冗长的方式?

2 个答案:

答案 0 :(得分:2)

我真的只是在20分钟前寻找这个。我在模板中不知道,但您可以在model挂钩中执行此操作,这样就无需声明控制器:

model: function() {
    return Em.ArrayProxy.createWithMixins(Em.SortableMixin, {
        sortProperties: ['index'],
        content: this.get('store').find('widget', [1,2,3,4])
    });
}

编辑:当然,这会将某些域逻辑混合到您的路线中,因此它可能不是首选的方式,但这是我最终使用的。

答案 1 :(得分:2)

我要将此作为一个新答案添加,因为它是如此不同。这非常棘手,您需要根据您的确切需要对其进行修改,但这是基础知识。您将创建一个sorted-each组件。首先,模板:

<script type="text/x-handlebars" id="components/sorted-each">
    {{#each sortedContent}}
        {{yield}}
    {{/each}}
<script>

现在我们要声明组件类。我们声明了您将传递给组件的3个属性。然后我们创建了一个计算属性来对内容进行排序。然后,我们覆盖_yield方法,因为默认情况下,它会给我们错误的上下文。

App.SortedEachComponent = Em.Component.extend({
    content: null,
    key: null,
    reverse: false,

    sortedContent: function() {
        return Em.ArrayProxy.createWithMixins(Em.SortableMixin, {
            content: this.get('content'),
            sortProperties: [this.get('key')],
            sortAscending: !this.get('reverse')
        });
    }.property('content', 'key', 'reverse'),

    _yield: function(context, options) {
        var get = Ember.get,
            view = options.data.view,
            parentView = this._parentView,
            template = get(this, 'template');

        if (template) {
            Ember.assert("A Component must have a parent view in order to yield.", parentView);
            view.appendChild(Ember.View, {
                isVirtual: true,
                tagName: '',
                _contextView: parentView,
                template: template,
                context: get(view, 'context'), // the default is get(parentView, 'context'),
                controller: get(view, 'controller'), // the default is get(parentView, 'context'),
                templateData: { keywords: parentView.cloneKeywords() }
            });
        }
    }
});

最后,让我们使用它!

{{#sorted-each content=items sortKey=itemKey1 reverse=true}}
    Property1: {{itemKey1}}
    Property2: {{itemKey2}}
{{/sorted-each}}

您可能希望根据自己的喜好稍微修改组件,但正如您所看到的,它确实有效。 (至少它应该。如果有任何拼写错误,请告诉我。)

相关问题