I am having difficulty getting the create function of backbone.js to work. My main question, is where do nextModel, resp, xhr come from?
I thought it should be doing coll.add(model) (‘coz we’re trying to add a model to the collection).
Thank you.
create : function(model, options) {
var coll = this;
options || (options = {});
model = this._prepareModel(model, options);
if (!model) return false;
var success = options.success;
options.success = function(nextModel, resp, xhr) {
coll.add(nextModel, options);
if (success) success(nextModel, resp, xhr);
};
model.save(null, options);
return model;
},
UPDATE:
This is what I learned following clues from shesak. I tracked it down, from Create to Save then to Backbone.sync. The options.success at the end will correspond to this in Jquery
success(data, textStatus, jqXHR)Function, Array
A function to be called if the request succeeds. The function gets passed three arguments:
- the data returned from the server, formatted according to the dataType parameter
- a string describing the status
- and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. Which means, nextModel would come from the data of success(data, textStatus, jqXHR).
The
optionsobject, along with thesuccesscallback, are passed toBackbone.Model#save, which saves a copy of thesuccesscallback, overrides it with its own callback and callsBackbone.sync, which eventually calls$.ajaxwith the entireoptionsobject. Its jQuery’s (or Zepto’s) code that eventually calls the (overridden)options.successwith the JSON response from the server.The overridden success callback
set()s the response from the server on the model (the server, after saving the model, can return either the entire model of it or just some of the attributes in JSON format. This is done to allow the server to modify or normalize the model when saving it [like adding the newly created ID]), and passes the changed model (that changed model is what being referred to asnextModel) back to the saved copy of the originalsuccesscallback (the one defined inBackbone.Collection#create), which adds thatnextModel(as passed fromBackbone.Model#save, after being modified by the JSON response from the server) to the collection.If you just want to add a model to the collection, without saving it in persistent storage by the server, call
Backbone.Collection#adddirectly instead of create.