ember-model icon indicating copy to clipboard operation
ember-model copied to clipboard

Removing a newly created record / Edit form scenarios

Open ahacking opened this issue 10 years ago • 2 comments

Scenario 1: Create a new model for a form, user cancels before record is saved.

How to cleanup?

Scenario 2: User edits existing (or new) record and adds a new member to a hasMany relationship and then decides to cancel addition of the item.

How to cleanup?

I tried destroyRecord() but that calls into the adapter and attempts a server request even on new records that haven't been saved yet. Sincecreate() doesn't appear to require any help from the adapter, removing an unsaved record shouldn't call into the adapter either.

I looked closer and it seems that the constructor/class function unload() is closest to what is needed. I am experimenting with the following extension/overrides to Ember-Model which appear to be working in my limited testing:

unload: function() {
  this.constructor.unload(this);
}

deleteRecord: function() {
  if (this.get('isNew')) {
    var record = this;
    return new Ember.RSVP.Promise(function(resolve, reject) {
      Ember.run.later(record, function() {
        record.didDeleteRecord();
        resolve(record);
      }, 0);
  } else {
    this._super.apply(this, arguments);
  }

didDeleteRecord: function() {
    this.unload();
    set(this, 'isDeleted', true);
    this.trigger('didDeleteRecord');
}

Q: Is the above appropriate for removing an unsaved record from the object graph?

I noticed didDeleteRecord() by default does not perform the same cleanup as unload(). Is that intentional? Does it mean that by default hasMany relationships and the record cache is never cleared for deleted items?

I can work up a PR for this if its something you will consider for EM.

ahacking avatar May 05 '14 02:05 ahacking

For scenario 2 I think you can use HasManyArray.revert()

dwickern avatar May 05 '14 17:05 dwickern

@dwickern That will revert all unsaved changes to the array, and not just remove the specific model instance. eg adding 2 Address models to a Person,first add one address, accept/apply, then start adding another address and then cancel addition of that second address.

I think I will need to confirm that unload removes the model out of ALL relationships / record arrays, even relationships not explicitly defined on the model but relationships defined by other models (eg A has a relationship to B whilst B the record being unloaded doesn't have an inverse relationship back to A).

ahacking avatar May 27 '14 13:05 ahacking