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

1

5

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.

Dopp answered 27/4, 2015 at 22:58 Comment(0)
A
6

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.

Angiology answered 27/4, 2015 at 23:14 Comment(1)
Thank you! I had read your answer to a similar question on SO but I was missing the self part.Dopp

© 2022 - 2024 — McMap. All rights reserved.