Search code examples
ember.jsember-router

route.afterModel hook not being hit


The afterModel hook is not being hit when you attempt to transitionTo from a parent route to the same route.

I expected the afterModel hook to always fire.

Twiddle

Edit: It's kind of hard to understand unless you are can look at the twiddle but here's the code

// Controller/application.js
export default Ember.Controller.extend({
  appName: 'Ember Twiddle',
  actions: {
    goTo() {
        this.transitionToRoute('food');
    }
  }
});

// templates/application.hbs
<button onclick={{action 'goTo'}}>Food Options</button>
<br>
{{outlet}}

//router.js
const Router = Ember.Router.extend({
  location: 'none',
  rootURL: config.rootURL
});

Router.map(function() {
  this.route('food', function() {
    this.route('options');
    this.route('fruits');
    this.route('veggies');
  });
});

//routes/food.js
export default Ember.Route.extend({
  model() {},
  afterModel() {
    this.transitionTo('food.options');
  }
});

Clicking the food options button the first time correctly calls the afterModel in food route. Clicking it the second time does not hit the afterModel.


Solution

  • Refer AlexSpeller Diagonal to see what route structure, templates and route hooks are for a given ember route definition. Its an awesome graphical representation of the route structure.

    Question:

    I am in a sub route under food, say food/fruits. If I click the button again I expect to be taken to the food route and then redirected to options

    Answer: food route has no URL, as it is a parent route. You will always be in a child state of this route (e.g. food.index). So when you say transitionTo('food') that means you are transitioning to food.index route.

    URL /food/fruits - will execute food model hooks and fruits model hook.
    URL /food - will execute food/index model hook and it will not execute food model hook.

    So in your case, You can remove this.transitionTo('food.options') from food afterModel hook and you can introduce food.index route which has food options.

    Look at modified ember twiddle which includes index route.