14
votes

Is there a way to revert a change to an Ember Data model easily?

I have a model bound to an edit view. This view enables the user to cancel editing, at which point I'd like to revert the changes to the model. Is there an easy way to do this without cloning all the values off the side?

4
object.get('transaction').rollback()Bradley Priest

4 Answers

14
votes

Starting from Ember Data version 2, there are not transactions anymore, but you can reset models to their last status before saved editions with:

model.rollbackAttributes();
6
votes

Ember Data supports the concept of transactions. We can create a transaction and assign Ember data records to them and if we want to undo the changes we can call the transactions rollback() method. Also if we do not create an explicit transaction the records are assigned to a default transaction which can be rolled back by calling the rollback() method on the DS.store object itself.

5
votes

The name of the default transaction is named 'defaultTransaction'. In fact, when Embers commits, it uses this default transaction. I can't use directly rollback on the store directly.

Instead of using store.rollback, you should have something like:

store.get('defaultTransaction').rollback()

or (if you are in a router event manager)

event.get('store.defaultTransaction').rollback()
3
votes

You could also do a rollback on the model itself if it is in an "isDirty" state.

this.get('model').rollback();

Example

export default Ember.ObjectController.extend({

 actions: {
    cancelEditModel: function(){

        this.get('model').rollback();

        this.transitionToRoute('...');

        return false;
    }
  }
});