Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the least ugly way to force Backbone.sync updates to use POST instead of PUT?

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.

like image 414
aw crud Avatar asked Dec 15 '11 22:12

aw crud


4 Answers

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
})
like image 126
Andrés Torres Marroquín Avatar answered Nov 11 '22 03:11

Andrés Torres Marroquín


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)

like image 42
Maanas Royy Avatar answered Nov 11 '22 04:11

Maanas Royy


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

like image 8
Paul Avatar answered Nov 11 '22 03:11

Paul


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: {
        ...
like image 5
Scott Evernden Avatar answered Nov 11 '22 04:11

Scott Evernden