Created
February 8, 2013 18:35
-
-
Save elijahmanor/4740993 to your computer and use it in GitHub Desktop.
Overriding Backbone.sync to POST instead of PUT/DELETE/PATCH
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 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
did not work for me, instead i had to override sync method within Mode.