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

前端 未结 5 1576
走了就别回头了
走了就别回头了 2020-12-05 14:29

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

相关标签:
5条回答
  • 2020-12-05 14:42

    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)

    0 讨论(0)
  • 2020-12-05 14:50

    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: {
            ...
    
    0 讨论(0)
  • 2020-12-05 14:52

    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);
      }
    });
    
    0 讨论(0)
  • 2020-12-05 14:54

    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

    0 讨论(0)
  • 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
    })
    
    0 讨论(0)
提交回复
热议问题