当路线发生变化但模板保持不变时,如何让 onRendered 第二次变为 运行?

How do I get onRendered to run a second time when the route changes but the template remains the same?

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

Router.route('/project/:key/update', {
  ...
});

每次用户导航到 "edit project page" 我想关注项目名称输入。

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

这在从仪表板导航到任何给定的编辑项目页面时效果很好。但是,将 to/from 一个项目页面导航到另一个项目页面时,onRendered 函数不会重新运行,因此输入没有聚焦。

你可以像这样强制onRendered to reevaluate after a context change by adding a check for currentData inside of an autorun

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();
  });
});

详情请见this issue末尾。