2

我目前正在从 Ember 2.18 转移到 Ember 3.16。在我的模型中,如果创建了新实例,我会使用 ready 函数为关系创建默认值。

// 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'));
        }
    }
});

ready 函数具有访问时正确设置整个内部状态的优点this.isNew

尝试转向 ES6 类方法会变成这样:

// 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'));
        }
    }
}

但这失败了,因为this.isNew还不能访问内部状态。

TypeError: Cannot read property 'currentState' of null

有没有办法通过将其限制在模型中来解决这个问题?我想避免创建工厂或构建器服务。任何帮助将非常感激。

4

1 回答 1

0

使用 init() 方法而不是构造函数(不推荐使用 init 方法)。据我了解,建议对组件使用构造函数,而不是模型

init() {
  this._super(...arguments);
  //your code here
}
于 2021-02-16T14:14:27.990 回答