dthree
dthree

Reputation: 20740

Backbone why is change called on save?

I have a Backbone model that I want to update locally, but I don't know if the update is going to change anything in the model.

I don't want to run set on the model and call a save right after, as nothing might have changed.

So ideally, I just listen for a change event and then save it:

var Goat = Backbone.Model.extend({

  initialize: function() {
    this.on('change', function(){
      this.save();
    });
  }

});

var billy = new Goat({
  gruff: true
});

billy.set('gruff', true); // doesn't do anything
billy.set('gruff', false); // fires change

The problem with this is that calling save then apparently fires change, and so we go in the exciting endless circle.

Why would save trigger change? And if this is so, what is the correct way for me to achieve the above?

Upvotes: 0

Views: 118

Answers (1)

David Jones
David Jones

Reputation: 10219

I'm not sure that attaching save to a change event is such a good idea (I'm not sure it isn't a good idea either – I suppose it depends on the situation), but in answer to your question, you can check whether the model hasChanged before saving. You can read more about this in the Backbone documentation here.

var Goat = Backbone.Model.extend({
  initialize: function() {
    this.on('change', function() {
      if (this.hasChanged()) {
        this.save();
      }
    });
  }
});

Upvotes: 1

Related Questions