首页 > 解决方案 > 升级到 Ember-Data 2.14 破坏了 hasMany 上的计算过滤器

问题描述

我曾尝试在旋转中重现这个问题,但不幸的是旋转总是成功,但我希望这个错误对某人来说听起来很熟悉,他们可以为我指明正确的方向。

这是旋转: https ://ember-twiddle.com/9ee6f28479449b7b1859e4c090490775?openFiles=routes.parent.js%2C

所有名称都已更改,以使我们的数据安全人员感觉更好:

基础知识:我有一个模型“父母”,与“孩子”有异步“hasMany”关系。

children: hasMany('child', {async: true}),

然后我有一个绑定到 hasMany 的计算属性:

sons: Ember.computed.filterBy('children', 'type', 'son'),

然后我为 firstObject 取别名以获取“儿子”数组中的第一项:

firstSon: Ember.computed.alias('sons.firstObject')

在父 route.setupController 中,我创建了一个新的“儿子”对象:

setupController: function(controller, model) {
    this._super(...arguments);
    var toy = this.get('store').createRecord('toy', {
      type: 'latte'
    });
    this.get('store').createRecord('child',
        {parent: model, type: 'son', toy: toy,
        name: 'Tyler'});
  }

使用 Ember 2.14 和 Ember-Data 2.13 或任何较低的匹配版本组合,这可以正常工作,我的模板可以毫无问题地引用 parent.firstSon。

一旦我将 Ember-Data 升级到 2.14,当我到达我想要的路线时, parent.children 有正确的孩子,但 sons: filterBy 为空,因此 sons.firstObject 的别名也为空。(通过 Ember 检查员验证)

提醒:我链接的 twiddle 确实有效,它是我的应用程序中更复杂的版本失败了。

升级的简单行为会破坏它 - 不会发生其他代码更改。

我在 ember-data github 中看到了一些类似的问题:这个问题:https ://github.com/emberjs/data/issues/4974 类似,但它似乎从 2.12 开始,并且似乎与新的“hasMany”调用有关避免加载数据。我只是绑定到实际的 async hasMany

https://github.com/emberjs/ember.js/issues/16258引用了一个类似的问题,但它仅从 Ember 3.0.0 开始并且在 2.18 中不存在 - 我的问题发生在 2.14.1 到 ~2.18

有什么想法可能已经坏了吗?

标签: ember.jsember-data

解决方案


看起来这是惰性 hasMany 创建的另一个问题。我调用了我所做的 afterModel:

  afterModel: function(model) {
    var parentPromise = this._super(...arguments);
    var loadChildren = () => {
      return model.get('children').then(children => {
        this.set('children', children);
      });
    };
    return (parentPromise && parentPromise.then) ? parentPromise.then(loadChildren) : loadChildren();
  },

并将 setupController 更改为:

  setupController: function(controller, model) {
    this._super(controller, model);

    var hasSons = model.get('sons').length > 0;
    if(!hasSons) {
      var toy = this.get('store').createRecord('toy', {...etc});
      var source = this.get('store').createRecord('child',
        {parent: model, type: 'son', toy: toy});
      this.get('children').removeObject(son).pushObject(son);
    }
  },

现在我恢复了旧功能注意:this.get('children').removeObject(son).pushObject(son); 是从https://github.com/emberjs/data/issues/4974推荐的 ,我确实需要 removeObject 和 pushObject 才能让它工作


推荐阅读