将变量用于Ember类中的数组键命名

时间:2018-06-26 13:54:39

标签: javascript ember.js ecmascript-6

我有一个如下的Ember组件类;

import Ember from 'ember';
import myappconstants from '../utils/constants';

export default Ember.Component.extend({
    constants: myappconstants.FIELD_CONSTANTS.SECTION_1,
    myConfigs: {
        [myappconstants.FIELD_CONSTANTS.SECTION_1.FIELD_1] : {fieldName:"my__label__1", type:"text"},
        [myappconstants.FIELD_CONSTANTS.SECTION_1.FIELD_2] : {fieldName:"my__label__2", type:"text"}        
    }
})

我的问题在我的组件类中,我想以略有不同的方式定义“ myConfigs”键。这是因为定义最多可以增加到20个左右,将来任何名称更改都必须在多个地方进行。

所以我希望将其定义为

myConfigs: {
        [this.constants.FIELD_1] : {fieldName:"my__label__1", type:"text"},
        [this.constants.FIELD_2] : {fieldName:"my__label__2", type:"text"}      
    }

使用上面的代码,我得到一个错误; 无法读取未定义的属性“常量”

是否可以实现上述命名?

2 个答案:

答案 0 :(得分:1)

如果要使myConfigsconstants属性相关,可以使用computed property

答案 1 :(得分:1)

您可以使用与组件类一起获得的willRender钩子,并使用.set()来设置myConfigs属性。

它看起来像这样:

import Ember from 'ember';
import myappconstants from '../utils/constants';

export default Ember.Component.extend({
  willRender() {
    const sec1Constants = myappconstants.FIELD_CONSTANTS.SECTION_1;

    this.set('myConfigs', {
      `${sec1Constants.FIELD_1}`: {fieldName:"my__label__1", type:"text"},
      `${sec1Constants.FIELD_2}`: {fieldName:"my__label__2", type:"text"}    
    });
  }
});

注意:如果您选择在.set()上进行任何类型的myConfigs,则要使用Ember Object代替POJO作为设置对象。

相关问题