Skip to content

Instantly share code, notes, and snippets.

@elijahmanor
Created February 8, 2013 18:35
Show Gist options
  • Save elijahmanor/4740993 to your computer and use it in GitHub Desktop.
Save elijahmanor/4740993 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`
@chris-ramon
Copy link

did not work for me, instead i had to override sync method within Mode.

    sync: function(method, model, options) {
      // overriding method, to do POST instead of PUT.
      return Backbone.sync('create', model, options);
    },

@seriyvolk83
Copy link

@chris-ramon Your solution is wrong. If model will try todelete object it will send POST instead of DELETE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment