rockandrollwithemberjs / rarwe-issues

Errata and updates for the Rock and Roll with Ember.js book
https://rockandrollwithemberjs.com
43 stars 4 forks source link

[Question] Why not leverage hooks inside Route class? #477

Closed lljr closed 4 years ago

lljr commented 4 years ago

This is sort of a follow-up from https://github.com/rockandrollwithemberjs/rarwe-issues/issues/476.

By the end of chapter 10, we are using the Router service to warn the user from unsaved changes in the bands.new Route. We rely on @service router to accomplish the task. Not only do we have to invoke the service, we also have to take into account all the complex hooks triggering to make the feature work (to get rid of the double prompting that happens when bands.band.index redirect hook triggers).

Just by the complex if nesting in bands.new controller's I had the feeling that this could be improved. I took a look inside the API Reference and found willTransition method in the Route class https://api.emberjs.com/ember/3.20/classes/Route/events. You'll have to scroll down to see the use of the event hook in an example. I rewrote the code in Chapter 10 and everything worked well. I did not have to add extra variables on the controller or use nested if statements in the controller's constructor. All of I had to do what defined the method in the bands.new Route. See below:

import Route from '@ember/routing/route';
import { action } from '@ember/object';

export default class BandsNewRoute extends Route {
  resetController(controller) {
    controller.name = '';
  }

  @action
  willTransition(transition) {
    if (this.controller.get('name')) {
      let leave = window.confirm('You have unsaved changes. Are you sure?');
      if (!leave) {
        transition.abort();
      }
    }
  }
}

Again, is there a reason we do not use this event hook? Is it because of something in Ember Classic that I'm not aware of?

balinterdi commented 4 years ago

Router events are deprecated and will be removed in 4.0: https://deprecations.emberjs.com/v3.x/#toc_deprecate-router-events