jax
jax

Reputation: 38583

Best way to rollback all changes to an Ember Data model

I am using ember-data to edit a user with automatic model resolution

this.route('user', function() {
  this.route('edit', { path: ':user_id'})
});

This works fine and the user can modify all aspects of the model DS.attribute, DS.belongsTo and DS.hasMany.

The user can navigate away in a number of ways, in which case all changes should be removed from the model.

The changes should only be applied if the user explicitly wants them to by clicking the Save button and the server request is successful.

I considered using ember-buffered-proxy but I am not sure how this will cope with DS.belongsTo and DS.hasMany relationships. Regardless, before saving the model I will need to do buffer.applyBufferedChanges(); before saving and if the server fails I am in the save situation as before.

The willTransition hook in the route seems like the obvious place to do this but how can I ensure all changes are removed from the model given rollbackAttributes() only works for DS.attribute controls.

Upvotes: 5

Views: 1898

Answers (1)

jacefarm
jacefarm

Reputation: 7411

Try utilizing the Ember.Route refresh() method inside the route's willTransition() action hook, like this:

action: {
  willTransition() {
    const unsavedModel = this.get('unsaved');
    if (unsavedModel) {
      this.refresh();
    }
  }
}

The refresh() method can be used for "re-querying the server for the latest information using the same parameters as when the route was first entered."

I've suggested a flag named unsaved, which can default to true, unless it has been set to false at some point during a successful save, prior to transitioning.

Upvotes: 1

Related Questions