2

I am currently transferring from Ember 2.18 to Ember 3.16. In my models I make use of the ready function to create default values for relationships if a new instance is created.

// app/models/human.js
import Model, { hasMany } from '@ember-data/model';

export default Model.extend({
    personalities: hasMany('personality')
    ready () {
        // because you should have at least one
        if (this.isNew) {
            this.get('personalities').pushObject(this.store.createRecord('personality'));
        }
    }
});

The ready function had the beauty that the whole internal state is set correctly when accessing this.isNew.

Trying to shift to the ES6 class approach would yield into somehting like this:

// app/models/human.js
import Model, { hasMany } from '@ember-data/model';

export default class HumanModel extends Model {
    @hasMany('personality') personalities;
    constructor () {
        super(...arguments);
        // because you should have at least one
        if (this.isNew) {
            this.personalities.pushObject(this.store.createRecord('personality'));
        }
    }
}

But this fails because this.isNew can't access the internal state yet.

TypeError: Cannot read property 'currentState' of null

Is there a way to address that by keeping that confined to the model? I would want to avoid creating a factory or builder service. Any help would be much appreciated.

1 Answers1

1

Use init() method instead of constructor (init method is not deprecated). As far as I understand, using constructor is recommended for components, not Models

init() {
  this._super(...arguments);
  //your code here
}
Igor
  • 592
  • 2
  • 9
  • 31