【问题标题】:EmberJs Async Firing ImmediatelyEmberJs 立即异步触发
【发布时间】:2023-03-28 02:30:02
【问题描述】:

我们有一个模型,该模型有多个 belongsTo 和 hasMany 关系设置为 async: true。 API 仅传递 ID。一旦页面加载,Ember 就会请求所有这些 ID。

这是预期的行为吗?我的印象是这些数据会在调用时加载。

我将如何弄清楚为什么会发生这些调用?

我们正在使用 Ember 1.13.9 和 Ember-data 1.13.11

编辑:事实证明,我们有一些东西扩展了我们的模型,它触及了所有这些异步关系。

【问题讨论】:

  • @torazaburo 的回答非常全面,但如果您觉得不够全面,您将不得不放弃有关您的应用的更多详细信息,例如您在模板中如何使用关系。

标签: ember.js ember-data


【解决方案1】:

我的印象是这些数据会在调用时加载。

“被叫”是什么意思?

说“在需要时加载”会更正确。

考虑以下几点:

// parent-model
children: hasMany('children', { async: true })

// parent-controller
displayChildren: false

// child-model
name: attr()

// template
{{#if displayChildren}}
  {{#each model.children as |child|}}
    {{child.name}}
  {{/each}}
{{/if}}

由于displayChildren 为假,模板中的循环将不会被执行。因此不需要孩子。因此,它们将不会被检索。当displayChildren 设置为true 时,子代将成为模板所需,并将被检索。如果displayChildren 的初始值为true,则渲染后立即检索孩子。

还有另一种情况会加载异步关系引用的记录:当为它们调用get 时(这是模板试图获取它们时在幕后发生的事情)。这个get 将返回一个实际值的承诺。因此,如果出于某种原因您需要或想要从程序逻辑中访问子项,您可以编写如下内容:

// parent-controller
someFunc() {
  this.get('model.children') . then(children => /* do something with children */)
}

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多