From the documentation:
-
Backbone.sync is the function that Backbone calls every time it attempts to read or save a model to the server. By default, it uses
jQuery.ajax
to make a RESTful JSON request and returns a jqXHR. -
The sync function may be overridden globally as
Backbone.sync
, or at a finer-grained level, by adding async
function to a Backbone collection or to an individual model.
So the code you initially have is actually good, but you should return
the Backbone.sync()
result like so:
app2.Pilot = Backbone.Model.extend({
url: POST_SUBMITTER.root + 'pilotdata/v1/pilot/',
sync: function( method, model, options ){
return Backbone.sync(method, this, jQuery.extend( options, {
beforeSend: function (xhr) {
xhr.setRequestHeader( 'X-WP-NONCE', POST_SUBMITTER.nonce );
},
} ));
},
});
Secondly, you should just pass the same method
that Backbone passes to your model’s custom sync()
function, just as you can see above. And although you don’t have to, I also use jQuery.extend()
to extend the options
object that’s passed to that sync()
function.
And with your other approach where you pass the header when you call your model’s fetch()
function, it does work, but extending the sync()
function is much better since you don’t need to specify the header for each request. 🙂