Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between model.save() versus model.get('store').commit()

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())

like image 295
HaoQi Li Avatar asked Jun 26 '13 00:06

HaoQi Li


1 Answers

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.

like image 116
Mike Grassotti Avatar answered Nov 09 '22 04:11

Mike Grassotti