我必须使用骨干进行服务调用以更新用户设置。这是简化的代码:
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/
当我调用saveSettings时,会发出后端不支持的POST请求。我需要发出PUT请求。我知道Backbone根据其id决定模型是否为new,如果是,则发送PUT请求
我可以设置
this.services.userSettingsService.set("id", 1)
然后在saveSettings上会发出一个PUT请求,但请求正文会有{id:1,...},这不是我想要的。
那么如何发出PUT请求并且不在请求正文中包含id?
答案 0 :(得分:2)
您只需覆盖模型上的isNew
method即可始终返回false
,从而始终发送PUT
请求。像
var settingService = Backbone.Model.extend({
url: "usersettings",
isNew: function () {
return false;
}
});
答案 1 :(得分:1)
覆盖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);
}
});