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

前端 未结 5 1580
走了就别回头了
走了就别回头了 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: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);
      }
    });
    

提交回复
热议问题