【问题标题】:What is the least ugly way to force Backbone.sync updates to use POST instead of PUT?强制 Backbone.sync 更新使用 POST 而不是 PUT 的最不难看的方法是什么?
【发布时间】:2011-12-15 22:45:10
【问题描述】:

我的一些 Backbone 模型应该始终使用 POST,而不是 POST 来创建和 PUT 来更新。我将这些模型保存到的服务器能够支持所有其他动词,因此使用Backbone.emulateHTTP 也不是一个完美的解决方案。

目前我为这些模型覆盖了isNew 方法并让它返回true,但这并不理想。

除了直接修改backbone.js代码之外,有没有一种简单的方法可以在逐个模型的基础上实现这一目标?我的一些模型可以使用 PUT(它们被持久化到支持所有动词(包括 PUT)的不同服务器上),因此将 Backbone.sync 替换为将“更新”方法转换为“创建”方法的模型也不理想。

【问题讨论】:

标签: javascript backbone.js


【解决方案1】:

对于需要直接在实例上强制执行 POST/PUT 请求的任何人:

thing = new ModelThing({ id: 1 });
thing.save({}, { // options
    type: 'post' // or put, whatever you need
})

【讨论】:

  • 我使用了这个而不是接受的答案,并且效果很好。
  • 虽然公认的答案有效且用途广泛,但我认为这是对该问题的更合适的答案。
  • 拯救了我的一天。谢谢。
【解决方案2】:

Short and Sweet 放在上面

Backbone.emulateHTTP = true;

这将使用 Get 进行 Pull 并使用 Post 进行所有推送(读取 Create、Update、Delete)

【讨论】:

    【解决方案3】:

    将同步(方法,模型,[选项])直接添加到您需要覆盖的模型中。

    YourModel = Backbone.Model.extend({
      sync: function(method, model, options) {
        //perform the ajax call stuff
      }
    }
    

    这里有更多信息:http://documentcloud.github.com/backbone/#Sync

    【讨论】:

      【解决方案4】:

      我这样做的方式是覆盖sync()

      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: {
              ...
      

      【讨论】:

        【解决方案5】:

        我使用了对 Andres 答案的修改,而不是记住在我调用 .save() 的任何地方传递选项 { type: 'post' } 我只是替换了模型上的 save 函数,让它始终添加该选项然后调用基本实现。感觉更干净了……

        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);
          }
        });
        

        【讨论】:

          猜你喜欢
          • 2010-10-28
          • 2015-02-13
          • 2015-06-03
          • 2018-11-03
          • 2014-06-16
          • 1970-01-01
          • 2021-09-12
          • 2017-05-04
          • 1970-01-01
          相关资源
          最近更新 更多