EmberJS,如何在子模板中访问父控制器中的模型

EmberJS, How access in a child template to the model in the parent controller

本文关键字:访问 控制器 模型 EmberJS      更新时间:2023-09-26

我有这个router:

// app/router.js
Router.map(function() {
  this.route('battle', function(){
    this.route('combats');
  })
});

在战斗路线中,我可以使用轻松访问战斗模型

// app/routes/battle/combat.js
this.modelFor('battle');

但如果我想在战斗模板中访问这个模型,事情就会变得复杂:

// app/templates/battle/combats.hbs
<h1>Combats for Battle {{<how to access to the battle>.title}}</h1>
{{#each model as |combat|}}
  {{combat.date}}
{{/each}}

我已经解决了从作战路线向作战控制员发送属性的问题:

// app/routes/battle/combat.js
setupController: function(controller, model) {
  controller.set('content', model);
  controller.set('battle', this.modelFor('battle'));
}

但我不知道这是否是正确的方式,在我看来,它看起来太过间接,就像你必须做出一个很长的变通办法才能在模板中使用这个属性。

这取决于您希望代码的通用性。对于您的特殊用例,可能适合在combats.js中的模型挂钩中使用Ember.RSVP.hash,如下所示:

model(){
    return Ember.RSVP.hash({
        combats: //here your combat.js model code,
        battle: this.modelFor('battle');
    })
}

然后您可以删除setupController函数并将模板重写为:

<h1>Combats for Battle {{model.battle.title}}</h1>
{{#each model.combats as |combat|}}
  {{combat.date}}
{{/each}}