Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should server respond to backbone sync

Some newbie questions about backbone.js' save and sync.

  1. After calling save/sync functions, what type of response does backbone expect from the server? Is any specific post-processing required after the response is received?

  2. How does backbone know whether the model already exists on the server? From the documentation I see that each model has an isNew that checks for whether there is an "id". So "id" is the id from the server, whereas "cid" is what backbone creates for each model. Correct? If so, what are the general steps for the server to inform backbone what the id of a model is, when:

    a) the model is first created and synced,

    b) subsequently when the model is fetched,

    c) or when the model is populated on page load?

Thanks for help.

like image 359
fortuneRice Avatar asked Jun 18 '11 05:06

fortuneRice


People also ask

When backbone wants to save or read a model to the server it calls out a function called as?

10) What is the usage of Backbone. sync? When Backbone. js wants to save or read a model to the Server, it calls out a function called Backbone.

What is the usage of backbone sync?

Backbone. sync is a function that is called every time when Backbone. js tries to read or save a model to the server. It is used to display the state of the model.

What is Backbone framework?

Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).


1 Answers

Answers to your questions:

  1. When you get a response back from the server, the response data goes through the parse method. For models, the parse method must respond with an attributes hash which will be used in a 'set' call to the model. For collections, the parse method must respond with an array of attributes hashes representative of the models to be maintained by the collection. In each case, there are default implementations which use the raw response object. If your response does not return usable hashes, then you need to provide your own parse method which does what you want.

  2. You are correct on your statement about how isNew works. Your server response must provide some sort of id that you either use or transform into an id attribute on the model in the parse method. The transform would be required if your server response does not call the object id as an attribute called 'id'. I think your entire second question hinges on your proper understanding of the parse method. This method must return an attributes hash which includes also the 'id' attribute.

like image 162
Bill Eisenhauer Avatar answered Oct 20 '22 12:10

Bill Eisenhauer