我在骨干网中运行此代码,将一些数据保存到服务器,
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()) {
console.log("MODEL IS NEW");
this.collection.add(this.model);
}
return this.model.save({ name: this.$("#group-name").val()}, {
async: false,
wait: true,
success: function() {
//console.log($this, "THIS");
console.log('Successfully saved!');
this.contentView = new app.GroupModalContentView({
model: $this.model,
collection: $this.collection,
parent: this
});
this.contentView.render();
return $this.cancel();
},
});
}
};
第一次运行它时工作正常,但如果我在保存第一段数据后直接再次运行它不会保存新数据,它只会更新上次保存的数据。所以我第一次保存它会运行POST请求,下次运行PUT请求时,为什么会这样?
我不确定你是否需要这个,但这是我的初始函数 -
GroupModalHeaderView.prototype.initialize = function() {
_.bindAll(this)
}
答案 0 :(得分:1)
您的视图附加了一个模型对象。据我所知,你填写一些表格,把他们的数据放到模型和保存模型。但是你总是有单个模型对象,而你只更新它的数据。如果要在保存模型后创建新对象,只需添加一行:
this.model = new YourModelClass();
在line console.log之后('Successfully saved!');
答案 1 :(得分:0)
来自骨干文档:
如果模型是新的,则保存将是"创建" (HTTP POST),如果 模型已经存在于服务器上,保存将是"更新" (HTTP PUT)。
如果您想要发布请求,即使模型是新的,只需覆盖默认的保存实现,并使用' create'来调用Backbone.sync(方法,模型,[选项])。作为通过的方法。