Skip to content

Instantly share code, notes, and snippets.

@ismnoiet
Forked from elijahmanor/backbone-sync-override.js
Created February 12, 2017 13:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ismnoiet/57367a53203427368a82878e21e8b3e6 to your computer and use it in GitHub Desktop.
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