10

What is the difference between

// 'this' is the controller
this.get('model').save();

and

// 'this' is the controller
this.get('model').get('store').commit();

? Of the little testing I did, they both gave me the same results. Which one should I use?

I looked into the first one, and it calls

DS.Model = Ember.Object.extend(
  ...
  save: function() {
    this.get('store').scheduleSave(this);

    var promise = new Ember.RSVP.Promise();

    this.one('didCommit', this, function() {
      promise.resolve(this);
    });

    return promise;
  }, 

So the question then becomes, what's the main difference between this.get('store').scheduleSave(this) and this.get('store').commit()?

DS.Store = Ember.Object.extend(DS._Mappable, {
  ...
  scheduleSave: function(record) {
    get(this, 'currentTransaction').add(record);
    once(this, 'flushSavedRecords');
  },
  ...
  /**
    This method delegates committing to the store's implicit
    transaction.

    Calling this method is essentially a request to persist
    any changes to records that were not explicitly added to
    a transaction.
  */
  commit: function() {
    get(this, 'defaultTransaction').commit();
  },

I'm not sure which one is better. I'm leaning towards save() because it seems to wrap around the store.

(I couldn't find these code on github, don't know if the github or the amazonaws version of emberjs is the latest. Here is the similar versions on github: model's save() which calls store's scheduleSave(), and store's commit())

user2431285
  • 661
  • 11
  • 19
HaoQi Li
  • 11,970
  • 14
  • 58
  • 77

1 Answers1

7

Which one should I use?

I'd recommend using this.get('model').save()

what's the main difference between this.get('store').scheduleSave(this) and this.get('store').commit()?

If you are saving many records during the same run loop, scheduleSave will batch changes so that multiple records will get saved in the same transaction. In some cases commit might cause changes to other records to be persisted.

Mike Grassotti
  • 19,040
  • 3
  • 59
  • 57
  • Thanks Mike for the answer. I'm not quite sure what you mean by "In some cases `commit` might cause changes to other records to be persisted."? Can you provide a small example? – HaoQi Li Jun 26 '13 at 21:07
  • 1
    Sure. Say your app lets users edit a few different kinds of data all on the same screen. In each section there is a form with some text inputs and a save/cancel button. User edits text in one form, then starts editing text in the other one. When they hit save on the 2nd form would expect it not to save the first. If you use commit, both records would be saved. – Mike Grassotti Jun 27 '13 at 19:18