我目前正在从 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
有没有办法通过将其限制在模型中来解决这个问题?我想避免创建工厂或构建器服务。任何帮助将非常感激。