Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js routing - conditionally prevent route/state change

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/

like image 657
Wesley Workman Avatar asked Jul 23 '12 17:07

Wesley Workman


Video Answer


2 Answers

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.

like image 104
hjdivad Avatar answered Sep 22 '22 23:09

hjdivad


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

like image 40
Wesley Workman Avatar answered Sep 26 '22 23:09

Wesley Workman