1

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?

user1031947
  • 6,294
  • 16
  • 55
  • 88
  • 1
    Change gets the model passed in as the first arg, so you can simplify your handler to: `function(model) { model.save(); }` (and then you won't have to bother with `self`). – machineghost Apr 01 '13 at 22:16

2 Answers2

1

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.

machineghost
  • 33,529
  • 30
  • 159
  • 234
  • It seemed to work for me, except I used _self.model.save(null, {silent: true})_. The reasons are discussed at this [question](http://stackoverflow.com/questions/5757555/how-do-i-trigger-the-success-callback-on-a-model-save). – Silveri Dec 15 '14 at 09:54
0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Brian
  • 1,026
  • 1
  • 15
  • 25