Router Hooks and Events
In this lesson, you’ll learn about route hooks and route events in Ember.js.
We'll cover the following
Tuning
It’s not a coincidence that this is the third chapter about routing. Ember’s routing mechanism is very powerful, and you can wield it as a weapon against different types of challenges that come your way if you know its ins and outs.
In this chapter, we’ll improve our app in a few different ways and use some routing concepts to achieve it. First, let’s discuss route hooks and actions some more.
Route hooks
In the Nested routes chapter, you saw how the router traverses each route level when transitioning to the destination route. It was a simplified model since it only mentioned the model
hook being called for each route. The truth is somewhat more complex. It’s not only the model
hook but several model hooks that are called in succession.
The first one is beforeModel
. Since it gets called before the resolved model is known, the only parameter it receives is the current route transition:
beforeModel(transition) {…}
Next up is the familiar model
hook. In addition to the transition, it also receives the params from the URL, which are parsed according to the routing tree:
model(params, transition) {…}
Once the model is resolved, the afterModel
hook is called with the model and the transition object:
afterModel(model, transition) {…}
So, at each level of a route transition, the beforeModel
, model
, and afterModel
hooks are called for the particular route, with one exception that we are going to cover later. When these have all run for all levels of the transition, the transition is considered validated. It is only then that the next hook, called setupController
, is entered:
setupController(controller, model, transition) {…}
We briefly discussed and used the setupController
hook in the Controllers chapter. As its title suggests, its main job is to set up the controller belonging to the route. The default implementation sets the controller’s model
property to the model that was previously resolved. If this is the desired behaviour, we do not need to use the setupController
hook.
The following graph helps us visualize how the router calls each model hook for each route:
Get hands-on with 1200+ tech skills courses.