我现在正在开发应用程序,当我创建一个组时,保存功能工作得很好,模型被添加到集合中,并保存到数据库中,但是如果我想编辑刚刚创建的组,当我点击“保存”,创建了新模型(和 POST 请求),而不是编辑数据并触发 PUT 请求。这是我的保存功能 - 在编辑现有模型时我没有触发 PUT 请求有什么原因吗?
GroupModalHeaderView.prototype.save = function(e) {
var $collection, $this;
if (e) {
e.preventDefault();
}
$this = this;
if (this.$("#group-name").val() !== "") {
$collection = this.collection;
if (this.model.isNew()) {
this.collection.add(this.model);
}
return this.model.save({ name: this.$("#group-name").val()}, {
async: false,
wait: true,
success: function() {
var modelID = $this.model.get('id');
return this.modal = new app.GroupModalView({
model: $this.collection.get(modelID),
collection: $this.collection
});
}
});
}
};
这是我的模型默认值,
Group.prototype.defaults = {
user_id: "",
name: "New Group",
email: "",
url: "",
telephone: "",
mobile: "",
fax: "",
people: ""
};
这是this.model
保存之前的console.log,
Group {cid: "c116", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object…}
_changing: false
_events: Object
_pending: false
_previousAttributes: Object
email: ""
fax: ""
mobile: ""
name: "New Group"
people: ""
telephone: ""
url: ""
user_id: ""
wait: true
__proto__: Object
attributes: Object
changed: Object
cid: "c116"
collection: GroupCollection
id: 189
__proto__: ctor
最佳答案
Backbone.js 触发 POST 请求而不是 PUT 的原因是因为您的模型没有与其关联的唯一标识符 id
。如果没有 id
与您的模型关联的属性,Backbone.js 将始终触发 POST 请求以将新条目保存到数据库。
来自 Backbone 站:
save model.save([attributes], [options]) ... If the model isNew, the
save will be a "create" (HTTP POST), if the model already exists on the server, the save will be an "update" (HTTP PUT).
阅读this SO question了解更多信息。
关于javascript - 模型创建新行而不是进行编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17697708/