现有模型上的 .save() 导致 POST 而不是 PUT [英] .save() on existing model causes POST instead of PUT
问题描述
我在保存对集合中单个模型的更改时遇到了一些问题.已加载(通过集合 .reset())的模型正在发出 POST(就像它们是新的)而不是预期的 PUT.
I'm having some trouble saving changes to individual models in a collection. Models that have been loaded (via a collection .reset()) are issuing a POST (as if they were new) instead of the expected PUT.
这是我正在采取的方法:
Here's the approach I'm taking:
AppView
通过 this.model.childcollection.reset(JSON DATA FROM SERVER) 加载子集合;
Loads the child collection via this.model.childcollection.reset(JSON DATA FROM SERVER);
在它的渲染函数中,为集合中的每个项目创建一个新的子视图并渲染它:
In it's render function, creates a new childview for each item in the collection and renders it:
render: function() {
var el = this.el;
this.model.childcollection.forEach(function(s) {
var view = new ChildView({ model: s });
el.append(view.render().el);
});
return this;
},
子视图
在它的一个事件中,它改变了底层模型的一些值并调用了保存:
In one of its events it is changing some values of the underlying model and calling save:
this.model.set(
{
ValueA: somevalue,
ValueB: somevalue
},
{
error: function() {
console.log("Error saving model");
},
success: function() {
console.log("Model change saved");
}
});
this.model.save();
观察:
- 调用POST(没有子ID)而不是PUT(有子ID)
- 子元素设置了 Id
谁能告诉我为什么会发生这种情况?
Can anyone tell me why this may be happening?
推荐答案
backbone 使用模型的 .id
属性(不是属性)来确定它应该放置还是发布,如下所示源代码:https://github.com/documentcloud/backbone/blob/master/骨干.js#L344-346
backbone used the .id
property (not attribute) of the model to determine whether it should put or post, as shown here in the source code: https://github.com/documentcloud/backbone/blob/master/backbone.js#L344-346
如果它在保存现有模型时进行发布,则意味着 .id
属性未正确加载.即使对 model.get("id")
的调用返回正确的结果,对 model.id
的调用也必须返回正确的结果才能知道这是不是新型号.
if it's doing a post when saving an existing model, this means the .id
property wasn't loaded correctly. even if a call to model.get("id")
returns the right result, a call to model.id
must return the right result for it to know that this is not a new model.
确保您模型的 id 属性称为 id
,如果不是,请确保在您的模型上设置 idAttribute
:
be sure you're model's id attribute is called id
, or if it's not, be sure to set the idAttribute
on your model:
MyModel = Backbone.Model.extend({
idAttribute: "myCustomId"
});
这篇关于现有模型上的 .save() 导致 POST 而不是 PUT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!