Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly happens when you save a Backbone model?

What exactly happens when you save a Backbone model? Here's the best I can piece together by reading the documentation here:

  1. model.save([attributes], [options]) is called
  2. A "change" event is fired (but only if the attributes are new)
  3. The server is notified of the change?
  4. A "sync" event is called once the server returns

But I'm a Backbone noob and I'm sure someone else could do a way better job of explaining.

I'm partly just curious what happens. I'm also having trouble understanding how Backbone comes up with the JSON object it sends to the server. I'm having a separate problem where the JSON object is not what I want it to be, but I don't know how to change it.

like image 454
Jason Swett Avatar asked Jul 10 '12 14:07

Jason Swett


1 Answers

The detailed process can be found in the annotated source code for Backbone.Model.save and Backbone.sync.

If you ignore options.wait and options.silent, your decomposition is mostly correct.

When you issue a model.save:

  1. the attributes passed to the function are set, a change event is fired if the values changed
  2. save delegates the request to model.sync or Backbone.sync
  3. sync serializes the data to a JSON string by calling JSON.stringify(model.toJSON())
  4. An Ajax request is sent to sent to server, a POST request for a new object, a PUT for an update. The target URL is defined by model.url (or collection.url/id)
  5. When the request completes, the model is updated with the server response, if any, and triggers a change event accordingly.
  6. Success or error callbacks are called, a sync event is triggered if no success callback is defined.

Usually, you can customize this behaviour by overriding model.toJSON or model.sync

like image 78
nikoshr Avatar answered Sep 20 '22 20:09

nikoshr