Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 344
Lance Anderson Avatar asked Apr 27 '15 22:04

Lance Anderson


1 Answers

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.

like image 137
David Weldon Avatar answered Oct 08 '22 01:10

David Weldon