Lance Anderson
Lance Anderson

Reputation: 493

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

I have an iron-router route for updating the data of a specific project:

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

Each time the user navigates to an "edit project page" I want to focus the project-name input.

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

This works great when navigating from the Dashboard to any given edit project page. However, navigating to/from one project page to another the onRendered function doesn't rerun and consequently the input is not focused.

Upvotes: 5

Views: 1251

Answers (1)

David Weldon
David Weldon

Reputation: 64312

You can force onRendered to reevaluate after a context change by adding a check for currentData inside of an autorun like this:

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

For more details, see the end of this issue.

Upvotes: 6

Related Questions