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`
@chris-ramon

This comment has been minimized.

Copy link

@chris-ramon chris-ramon commented Jun 12, 2014

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

This comment has been minimized.

Copy link

@seriyvolk83 seriyvolk83 commented Mar 5, 2019

@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