Some newbie questions about backbone.js' save and sync.
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?
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.
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.
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.
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).
Answers to your questions:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With