Gabriel Theron
Gabriel Theron

Reputation: 1376

Emberjs: stop and retry transitions in willTransition

When a user is about to leave the present route, I'd like to display a warning and let him choose between leaving (and losing changes) and staying in the current route.

In order to catch all possible transitions, I need to do this in the routes willTransition method.

I'm attempting to abort() and then retry() the transition if the user chooses to. But the retry doesn't seem to have any effect. It should be noted that it is called asynchronously. Here's a twiddle that demonstrates that: https://ember-twiddle.com/b6d8ddb665ff79f2988277912916e77b?openFiles=routes.my-route.js%2C

Here's my route example route:

import Ember from 'ember';

export default Ember.Route.extend({
  actions: {
    willTransition(transition) {
      transition.abort();
      Ember.run.later(function(){
        console.log('Transition... now!');
        transition.retry();
      }, 2000);

      return true;
    }
  }
});

The log shows up, but I never get redirected to the application route.

Upvotes: 0

Views: 638

Answers (2)

Ember Freak
Ember Freak

Reputation: 12872

When a user is about to leave the present route, I'd like to display a warning and let him choose between leaving (and losing changes) and staying in the current route.
For the above requirement, the below code is enough.

willTransition(transition) {
    if (!confirm('Are you sure to navigate ?')) {
        transition.abort();
        return false;
    }
    return true;
}

Upvotes: 1

Gennady Dogaev
Gennady Dogaev

Reputation: 5991

Take a look into log. You will see that "Transition... now!" appears there every 2 sec. That shows that willTransition works again and again. So you need some flag that allows you to go away. Updated twiddle

Upvotes: 4

Related Questions