Some of my Backbone models should always use POST, instead of POST for create and PUT for update. The server I persist these models to is capable of supporting all other ve
Short and Sweet is put this on Top
Backbone.emulateHTTP = true;
This will use Get for Pull and Post for All pushes (read Create, Update, Delete)
the way I've done it is to override sync()
thusly
Models.Thing = Backbone.Model.extend({
initialize: function() {
this.url = "/api/thing/" + this.id;
},
sync: function(method, model, options) {
if (method === "read") method = "create"; // turns GET into POST
return Backbone.sync(method, model, options);
},
defaults: {
...
I used a modification of Andres' answer and instead of havivng to remember to pass the option { type: 'post' }
everywhere that I call .save()
I instead just replaced the save
function on the model to have it always add that option then call the base implementation. It felt cleaner...
module.exports = Backbone.Model.extend({
idAttribute: 'identifier',
urlRoot: config.publicEndpoint,
save: function (attributes, options) {
// because the 'identifier' field is filled in by the user, Backbone thinks this model is never new. This causes it to always 'put' instead of 'post' on save.
// overriding save here to always pass the option use post as the HTTP action.
options = _.extend(options || {}, { type: 'post' });
return Backbone.Model.prototype.save.call(this, attributes, options);
}
});
add a sync(method, model, [options]) directly to your models you need to override.
YourModel = Backbone.Model.extend({
sync: function(method, model, options) {
//perform the ajax call stuff
}
}
Here's some more information: http://documentcloud.github.com/backbone/#Sync
For anyone who needs to force a POST/PUT request on the instance directly:
thing = new ModelThing({ id: 1 });
thing.save({}, { // options
type: 'post' // or put, whatever you need
})