Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Overriding Backbone.sync to POST instead of PUT/DELETE/PATCH
// The following could have been replaced by setting `Backbone.emulateHTTP = true;`
Backbone._sync = Backbone.sync;
Backbone.sync = function( method, model, options ) {
var beforeSend = options.beforeSend;
options = options || {};
if ( method === "update" || method === "delete" || method === "patch" ) {
options.beforeSend = function( xhr ) {
xhr.setRequestHeader( "X-HTTP-Method-Override", method );
if ( beforeSend ) { beforeSend.apply( this, arguments ); }
method = "create";
};
}
return Backbone._sync( method, model, options );
};
var Contact = Backbone.Model.extend({ urlRoot: "/contacts" });
var john = new Contact({ id: 42, firstName: "John", lastName: "Smith" });
john.save(); // POST instead of PUT with X-HTTP-Method-Override of `create`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment