ember.jsember.js-view

Ember hooks explanation


I have been working on Ember for about a month now but I am still confused about the various hooks in Ember. I know bits and pieces of everything but can't stitch them together. I understand the usage of model, beforeModel and afterModel hooks. What is setupController hook used for and when is it called in the lifecycle. Also what is renderTemplate hook used for. I have been using it to execute functionality that should be carried out everytime the template is rendered but after reading online, I found out that it is used when one wants to render another template in an outlet like:

renderTemplate: function() {
    this.render('favoritePost');
} 

If I define the both the model hook and the renderTemplate hook in the route, I start getting errors and nothing works after that. Where can I do things that should be done every time a template is loaded. I know I can do a similar thing using didInsertElement hook for a view but can't I do it without creating a view?


Solution

  • The best thing really would be for you to read the routing section in the ember guides.

    The setupController hook does exactly what its name says - it sets up the relevant controller (or controllers if you need it) with the model data. The model data can originate from model hook (given a manual url) or from a link-to helper/transitionToRoute call - so will be called every time you enter this route in either way. By default it will attach the model to the implied controller as the 'model' property.

    The renderTemplate hook is usually used only if you want to render a template/view that is not the one set by the naming convention for this route, or hook a different controller than the convention implied one. It can also be used to render into a specific outlet in a specific template. By default it will rendered the implied view/template using the implied controller as context.

    About your question where should you locate your code - as it is obviously has something to do with the view layer - you should definitely put it in the view, and not in the router. If you insist on putting it in the router - make sure you call this._super() when overriding these hooks.