0

I have an Ember component class as below;

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

My question is in my component class, I want to have the "myConfigs" keys defined in a slightly different way. This is because the definition can grow to around as many as 20 items & any name change in future would have to be done in multiple places.

So I want it to be defined as

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

With the above code, I get an error; Cannot read property 'constants' of undefined

Is it possible to achieve the above naming ?

user1297293
  • 96
  • 1
  • 6
  • Note that these aren't array keys, they're property names (`myConfigs` is a non-array object). – T.J. Crowder Jun 26 '18 at 13:58
  • In that code, `this` doesn't refer to your instance. To access `this`, you'd need to override [`init`](https://emberjs.com/api/ember/3.2/classes/Component/methods/init?anchor=init) and run code inside it. (But I don't know the Ember-specific details other than that it's `init`, so can't post an *answer*.) – T.J. Crowder Jun 26 '18 at 14:03
  • Almost a duplicate of [Self-references in object literal declarations](https://stackoverflow.com/q/4616202/218196), expect this is for keys instead of values. – Felix Kling Jun 27 '18 at 08:18

2 Answers2

1

You can use computed property if you want to make myConfigs dependent from constants property

Gennady Dogaev
  • 5,902
  • 1
  • 15
  • 23
1

You can use the willRender hook that you'll get with the component class, and use the .set() to set your myConfigs property.

It would look something like this:

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

Note: If you choose to do any sort of .set() on myConfigs, you'll want to use an Ember Object instead of a POJO for the set object.

Danielle Adams
  • 260
  • 1
  • 12