user1031947
user1031947

Reputation: 6664

Backbone Model save on change loops between client and server

In my backbone model, I call save when there is a change event.

myModel = Backbone.View.extend({

  initialize: function() {
    var self = this;
    self.model.on("change", function() { self.model.save(); });
  }

});

From the Backbone docs, I understand that Backbone expects to get a json object back from the server.

So I send the model back to the client. And backbone then updates the model, which triggers the change event again, which causes it to resave again.

What is the recommended way to prevent this behaviour?

Upvotes: 1

Views: 255

Answers (2)

Brian
Brian

Reputation: 1036

A cleaner way to write it would be:

//inside you model
initialize: function () {
    this.on('change',function(){ this.save(null,{silent: true}); });
}

As in the docs backbonejs.org/#Model-save.

The 1st arg is the attributes and the 2nd is the options.

Upvotes: 0

machineghost
machineghost

Reputation: 35770

In general in Backbone when you don't want side effects from your action you just pass a silent: true option. For instance:

self.model.on("change", function() { self.model.save({silent: true}); });

I haven't tested to ensure this solves your case, but I suspect it will.

Upvotes: 1

Related Questions