Ember event to better discard changes between the same route

I have an Ember list and an edit form. Each time the selected list item changes, the edit form discards any changes and loads a new model.

My problem is that it is impossible to undo the changes, since the deactivation of the event does not start.

For example, a transition from url/favs/123/editto url/favs/456/editdeactivate (and exit) an event DOES NOT fire. Thus, there is no way to correctly reject any changes.

Here is part of my code, I mean:

App.Router.map(function() {
    this.resource('favs', { path: '/favs' }, function() {
        this.route('new');
        this.route('edit', { path: ':fav_id/edit' })
    });
});

[...]

App.FavsEditRoute = Ember.Route.extend({
    deactivate: function() {
        var model = this.get('currentModel');
        if(model && model.get('isDirty')) {
            model.get('transaction').rollback();
        }
    },

    model: function(params) {
        return App.Fav.find(params.fav_id);
    },
});
+5
source share
3 answers

willTransition. Ember:

http://emberjs.com/guides/routing/preventing-and-retrying-transitions/

API, , , , , "".

:

App.FavsEditRoute = Ember.Route.extend({
  ...
  actions: {
    willTransition: function(transition) {
      controller = this.controllerFor('fav');
      if (controller.get('isDirty') &&
          !confirm("Are you sure you want to abandon progress?")) {
        transition.abort();
        return false;
      } else {
        controller.get("content").rollback();
        return true;
      }
    }
  }
});
+4

, . contextDidChange . Ember:

Ember.Route = Ember.Object.extend({
    /**
    @private

    Called when the context is changed by router.js.
  */
  contextDidChange: function() {
    this.currentModel = this.context;
  }
});

:

App.FavsEditRoute = Ember.Route.extend({
    deactivate: function() {
        this.doRollback();
    },
    contextDidChange: function() {
        this.doRollback();
        this._super();
    },
    doRollback: function(){
        var model = this.get('currentModel');
        if(model && model.get('isDirty')) {
            model.get('transaction').rollback();
        }
    }
});
+2

In Ember 2.2, the correct code (along the route):

actions: {
  saveScene: function (scene) {
    var _that = this;

    scene.save().then(function (response) {
      // on saveScene action, go to list route
      _that.transitionTo('scenes');
    });
  },

  willTransition: function (transition) {
    // on transition, if model has unsaved changes, revert them
    var model = this.controller.get('model');
    if (model && model.get('hasDirtyAttributes')) {
      model.rollbackAttributes();
    }
  }
}
+1
source

All Articles