如何使用传递给Ember组件的属性路径?

时间:2014-04-09 13:04:39

标签: ember.js

我想做这样的事情

App.FooComponent = Ember.Component.extend({
    tagName: 'ul',

    propertyPath: '',

    data: []
});

在foo-component.hbs中(这显然不起作用):

{{#each item in data}}
    <li>{{propertyPath}}</li>
{{/each}}

我会按如下方式使用该组件:

{{foo-component data=content propertyPath='name'}}

其中content是一个对象集合,每个对象都有一个&#39; name&#39;属性。

我尝试在组件中使用计算属性并绑定到该组件来执行此操作:

itemNames: function() {
    var propertyPath = 'data.@each.' + this.get('propertyPath');
    return this.get(propertyPath);
}.property(???)

但是这有如何设置依赖键以便重新计算属性的问题。

1 个答案:

答案 0 :(得分:0)

我会用这样的东西:

items: Ember.computed.map('data', function(dataObject) {
    return {
        name: dataObject.name,
        otherProp: dataObject.otherProp
    };
}).property('data.@each.{name, otherProp}')

声明一个计算属性,将data中的对象映射到其他对象。在您的函数中,您只需返回具有所需属性的对象(我使用nameotherProp)。然后,为了确保该属性在每个对象上监视nameotherProp属性,我使用.property()调用覆盖从属密钥。 (默认情况下,Ember.computed.map会为您调用.property('data.@each')。)

然后,在您的模板中:

{{#each items}}
    <li>{{name}}</li>
{{/each}}

编辑:

动态属性名称有点奇怪。一种方法是在创建时在类上声明一个计算属性。

init: function() {
    var propertyPath = this.get('propertyPath');

    this.reopen({
        propertyPathUpdater: function() {
            this.notifyPropertyChange('data');
        }.observes('data.@each.' + propertyPath)
    });
}

根据您的值更新的方式,您可能需要稍微弄清楚它,但希望您明白这一点。这个想法是Ember不喜欢动态属性。 :)

相关问题