this.model.save({
success: function(model, response){
console.log('success');
},
error: function(){
console.log('error');
}
})
模型已正确发布到处理保存的服务器,但不会触发成功回调。我需要从服务器发回一些东西吗?
save 的第一个参数是要保存在模型上的属性:
this.model.save( {att1 : "value"}, {success :handler1, error: handler2});
由于某些未知原因,上述方法都不适合我。在我的情况下,只有 api 没有被击中。
但后来在搜索此内容时,我遇到了 this link,其中有人尝试将 null
而不是 {}
作为第一个参数。
this.model.save(null, {
success: function (model, response) {
console.log("success");
},
error: function (model, response) {
console.log("error");
}
});
所以,这对我有用。希望这对你也有帮助。
您的服务器必须返回一个 JSON 对象。如果响应不是 JSON 对象,则不会触发回调。
如果为了成功,您的服务器没有返回 JSON 对象,请使用 dataType:"text" 选项执行保存,如下所示:
this.model.save([],{
dataType:"text",
success:function() {},
error:function() {}
});
使用此选项,它不会等待 JSON 响应,而是等待文本,因此将启动回调。
您可以按如下方式使用下划线库,因为主干已经依赖于此。请记住 save 的第一个参数必须具有属性,或者您可以只传递 {} 以防您要保存模型本身。
this.model.save({}, _.bind(function(model, response){
//Do whatever you want e.g.
this.collection.add(model)
}, this))
所以我有点困惑 - 我是否仍然需要传递所有属性才能调用保存事件?如果我的模型很大怎么办……我不想手动设置每个属性
我正在调用 model.save 并尝试执行以下操作:
this.model.save(
{
success: function (model, response) {
console.log('model saved');
}
});
好的,只是为了回答我自己的问题,以防有人发现这篇文章,我做了以下工作:
this.model.save({ id: this.model.get('id') },
{
success: function (model, response) {
console.log("success");
},
error: function (model, response) {
console.log("error");
}
});
编辑:由于某种原因我无法回复你,但我可以编辑
但是您不必设置 id: this.model.get('id')
您可以只传递一个空白对象,因为空白属性不会扩展属性,什么都不做:
this.model.save({}, {
success: function (model, response) {
console.log("success");
},
error: function (model, response) {
console.log("error");
}
});
以下是我用于骨干模型保存的代码。
this.model.save(model,{
success:function(model){
console.log("Saved Successfully");
},
error:function(model){
console.log("Error");
}
});
干杯
罗伊·乔丹
model
传递给 this.model
有点让人分心。model
应该是 attributes
,它们与 this.model
中的所有内容一起设置和保存
model.set(model.toJSON()); model.save()
。没有理由将模型设置为模型设置的内容。保存时将模型传递给自身是冗余的缩影。
对于那些想要保存模型而不更新属性的人,您可以执行以下操作:
model.once("sync", function(model, response, options){
//
});
model.once("error", function(model, response, options){
//
});
model.save();
在初始化函数中,将同步方法绑定到您定义的方法(onSaveSuccess)
initialize: function (options) {
this.model.on('sync', _.bind(this.onSaveSuccess, this));
},
onSaveSuccess: function() {
console.log('saved');
this.render();
},
这样,每当您运行 this.model.save() 时,如果您的同步成功,它将运行 onSaveSuccess 函数作为回调
不定期副业成功案例分享