Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js: How can I prevent transition on dirty model with async confirmation?

I have a pretty common situation: there is a dirty model and I want to show a confirmation if user tries to transition to any other route.

I have something like this to work with window.confirm confirmation dialog:

var EventRoute = Ember.Route.extend({
  actions: {
    willTransition: function(transition) {
      var event = this.modelFor(this.routeName);
      if (event.get('isDirty') && !confirm("Are you sure?")) {
        transition.abort();
      } else {
        event.rollback();
        return true;
      }
    }
  }
});

But if I want to use asynchronous confirmation (e.g. bootbox.js confirmation), how can I stop transition?

I've tried to return Ember.RSVP.Promise but it seems that willTransition doesn't support promises.

So the question is how is it possible to prevent transition to another route with async confirmation?

like image 844
Anthony Hell Avatar asked May 18 '14 16:05

Anthony Hell


1 Answers

You can use abort to cancel/pause the transition, then with that same transition instance you can call retry to attempt the transition again.

In the example included I'm stopping the transition, then a second later starting it again. You could launch your confirmation dialog and upon clicking ok/cancel use the transition object to continue the transition.

willTransition: function(transition){
  var self = this;
  if(!this.get('allowTransition')){
    console.log('transition abort');
    transition.abort(); 

    Em.run.later(function(){
      self.set('allowTransition', true);
      console.log('transition retry');
      transition.retry();
   }, 1000);
 }

http://emberjs.jsbin.com/gefituqo/1/edit

like image 160
Kingpin2k Avatar answered Oct 23 '22 06:10

Kingpin2k