Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  • Clicking a Cancel button
  • Clicking the Broswer Back button
  • Clicking the Save button, the remote request fails, then navigating away from the page.
  • Just Clicking some other link on the page which takes them somewhere else.

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.

like image 332
jax Avatar asked Nov 08 '22 16:11

jax


1 Answers

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.

like image 94
jacefarm Avatar answered Jan 04 '23 02:01

jacefarm