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 verbs, so using Backbone.emulateHTTP
is not a perfect solution either.
Currently I override the isNew
method for these models and have it return true
, but this is not ideal.
Other than modifying the backbone.js code directly, is there a simple way to achieve this goal on a model-by-model basis? Some of my models can use PUT (they are persisted to a different server that supports all verbs, including PUT), so replacing Backbone.sync with one that converts the 'update' method to 'create' is not ideal either.
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
})
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)
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
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: {
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With