如何在路由更改但模板保持不变的情况下第二次运行onRendered?

Lan*_*son 5 meteor iron-router

我有一个铁路由器路由来更新特定项目的数据:

Router.route('/project/:key/update', {
  ...
});
Run Code Online (Sandbox Code Playgroud)

每次用户导航到"编辑项目页面"时,我都想要关注项目名称输入.

template.onRendered(function() {
  this.$('form input[name="project_name"]').focus();
});
Run Code Online (Sandbox Code Playgroud)

当从仪表板导航到任何给定的编辑项目页面时,这非常有用.但是,导航到/从一个项目页面导航到另一个项目页面,该onRendered功能不会重新运行,因此输入不会集中.

Dav*_*don 6

您可以通过在自动运行内部添加对currentData的检查来强制onRendered在上下文更改后重新评估,如下所示:

Template.myTemplate.onRendered(function() {
  var self = this;
  this.autorun(function() {
    // hack to force the autorun to reevaluate
    Template.currentData();

    // insert onRendered code here
    self.$('form input[name="project_name"]').focus();
  });
});
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅此问题的结尾.