Ember.js routing - conditionally prevent route/state change
Asked Answered
S

3

12

I'm trying to figure out how to prevent or pause a route change. For my edit screens, if the user navigates away (back button or some other mechanism) when they have unsaved changes, I would like to prompt them to make sure they want to leave the page. Very similar to window.onbeforeunload, but via the router.

The statechart in previous versions of Ember gave you a transition object that you could use. It seems that in ember-latest, this is no longer the case. So what's the best way to go about this?


EDIT:

The above question is old and the answers listed are dated. Ember now has a native way to handle this. See docs: http://emberjs.com/guides/routing/preventing-and-retrying-transitions/

Socrates answered 23/7, 2012 at 17:47 Comment(0)
S
6

Ember's router now has a native mechanism to do this very easily. See docs: http://emberjs.com/guides/routing/preventing-and-retrying-transitions/

Socrates answered 26/12, 2013 at 2:28 Comment(0)
B
8

What you want to do is make your transitions conditional. Instead of using Ember.Route.transitionTo directly, you want something like:

var transitionAfterConfirmation = function(target){
  var defaultEvent = Ember.Route.transitionTo(target),
      event = function(stateManager, context){
          if( confirm("Really go?")){
              defaultEvent(stateManager,context);
          }
      };

  event.transitionTarget = target;

  return event;
};

see http://jsfiddle.net/hjdivad/KsHCN/ for an example.

Baribaric answered 26/7, 2012 at 16:2 Comment(1)
Really nice! I keep the link to your fiddle... :-)Constellate
S
6

Ember's router now has a native mechanism to do this very easily. See docs: http://emberjs.com/guides/routing/preventing-and-retrying-transitions/

Socrates answered 26/12, 2013 at 2:28 Comment(0)
L
2

I'm not sure it's possible since there is (perhaps I missed something) no handler available before exiting from a state. Looking at triggering enter state and enterState() code, it looks like you can't interrupt or cancel the transition between two states.

I think this is explained by Tom Dale in Allow canceling state transitions.

In your case, perhaps you could declare an intermediate state responsible to either redirect to the previous state if the user cancel, or go to the new state if the user accept. I have to say it's easier to write than to implement :(

Litalitany answered 23/7, 2012 at 22:57 Comment(1)
I would agree with Tom Dale's response on GitHub. This should be marked as the accepted answer.Spriggs

© 2022 - 2024 — McMap. All rights reserved.