Skip to content

Instantly share code, notes, and snippets.

@martinmaillard
Created September 30, 2014 18:12
Show Gist options
  • Save martinmaillard/e228e2c512bb622bf389 to your computer and use it in GitHub Desktop.
Save martinmaillard/e228e2c512bb622bf389 to your computer and use it in GitHub Desktop.
Ember: discard changes when leaving page
/**
* Rolls back changes on a model (and deletes new models) when leaving
* the page without saving. The user will also be notified if the model
* has changed when trying to leave the page.
*/
App.HandleModelChanges = Ember.Mixin.create({
deactivate: function() {
var model = this.get('controller.model');
model.rollback();
if (model.get('isNew')) {
model.deleteRecord();
}
},
actions: {
willTransition: function(transition) {
var model = this.get('controller.model');
if (model.get('isDirty') && !confirm('Do you really want to leave the page ? All the changes will be lost.')) {
transition.abort();
}
}
},
});
App.PostRoute = Ember.Route.extend(App.HandleModelChanges);
App.PostEditController = Ember.ObjectController.extend({
isSaving: false,
actions: {
cancel: function () {
this.transitionToRoute('post');
},
save: function () {
var self = this,
post = self.get('model');
self.set('isSaving', true);
post.get('errors').clear();
return post.save().then(function () {
self.transitionToRoute('post', post);
}).catch(function (error) {
// ...
}).finally(function () {
self.set('isSaving', false);
});
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment