检测何时填充了hasMany属性而没有结果

Detecting when a hasMany property has been populated with no results

本文关键字:结果 属性 hasMany 何时 填充 检测      更新时间:2023-09-26

我想做的事情似乎很简单,但我不太知道该怎么做。

我使用Emberjs 2.8.

我有以下具有async: true属性的模型:

models/my-model.js
import DS from 'ember-data';
export default DS.Model.extend({
  childModels: DS.hasMany('otherModel', {async: true})
});

我有一个组件,显示这些模型之一:

/components/my-component.js
import Ember from 'ember';
export default Ember.Component.extend({
   theModel: // model of type my-model here
})

my-model.childModels可能没有任何记录。我想做的是在模板中显示一个"没有找到孩子"的消息,如果是这样的话,但我只想在之后做这个对服务器进行异步调用并返回一个空响应。所以我希望模板看起来像这样:

templates/components/my-component.hbs
<div>
{{#if theModel.childModels.length == 0}}
   // display message saying there are no children
{{else}}
   {{#each theModel.childModels as |child}}
      // do something
   {{/each}}
{{/if}}
</div>

棘手的部分是知道关系是否已经从服务器填充。我不能只是检查.length == 0,因为在异步调用之前这是真的,我不希望DOM不必要地来回切换。我需要的是像theModel.childModels.isLoaded的东西,但通过查看文档后,我不确定如何实现这一点。

谁能建议一种方法来做到这一点?任何建议都将不胜感激。谢谢!

好吧,我现在觉得自己很傻,因为我找到了答案,它毕竟是在文档中。PromiseManyArray使用有isPending属性的PromiseProxyMixin。所以我可以创建一个计算属性,像这样:

  childModelsEmpty: Ember.computed('theModel.childModels', function () {
    return !this.get('theModel.childModels.isPending') && this.get('theModel.childModels.length') === 0;
  }),

这将告诉我服务器是否被击中并且返回空响应。