简体   繁体   English

使用骨干发送PUT请求

[英]Send PUT request with Backbone

I have to make service call with backbone to update user settings. 我必须使用主干进行服务呼叫以更新用户设置。 here is the simplified code: 这是简化的代码:

var settingService = Backbone.Model.extend({
  "url": "usersettings"
});


var SettingsView = Backbone.View.extend({
  initialize: function() {
    this.services = {
      "userSettingsService": new settingService()
    };
  },
  saveSettings: function() {
    this.services.userSettingsService.save({
      "currency": "USD",
      "dateFomat": "DD-MM-YYYY"
    })
  }
});

var settings_view = new SettingsView();

settings_view.saveSettings();

http://jsfiddle.net/ovg3kyqz/2/ http://jsfiddle.net/ovg3kyqz/2/

when I call saveSettings the POST request is made which is not supported by backend. 当我调用saveSettings时,发出了后端不支持的POST请求。 I need to make PUT request. 我需要提出PUT请求。 I know that Backbone decides whether model is new based on its id and if so will send a PUT request 我知道Backbone会根据其ID决定模型是否为新模型,如果是则将发送PUT请求

I can set 我可以设定

this.services.userSettingsService.set("id", 1)

and then on saveSettings a PUT request will be made but the request body will have {id: 1,...} which is not really what I want. 然后在saveSettings上将发出一个PUT请求,但是请求主体将具有{id:1,...},这并不是我真正想要的。

so how can I make a PUT request and not include id in the request body? 所以我该如何发出PUT请求,并且在请求正文中不包含ID?

You could simply override the isNew method on your model to always return false and thus always send a PUT request. 您可以简单地在模型上覆盖isNew方法 ,以始终返回false ,从而始终发送PUT请求。 Something like 就像是

var settingService = Backbone.Model.extend({
    url: "usersettings",
    isNew: function () {
        return false;
    }
});

And a demo http://jsfiddle.net/ehhwqm70/ 和演示http://jsfiddle.net/ehhwqm70/

An alternative to overriding isNew (that I find more explicit) would be to override model.sync : 另一种压倒一切isNew (我发现更明确)将覆盖model.sync

var settingService = Backbone.Model.extend({
  url: "usersettings",
  sync: function(method) {
    if (method === "create") {
      arguments[0] = "update";
    }
    return Backbone.sync.apply(this, arguments);
  }
});

Demo: http://jsfiddle.net/pytpfnar/1/ 演示: http//jsfiddle.net/pytpfnar/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM