我有一个处理表单的 View 。
此表单有一个在单击“保存”按钮时触发的事件:
var FormView = Backbone.View.extend({
initialize : function(options){
this.collection = new PlayerCollection( {url:options.url} );
this.collection.bind('add', this.addPlayer);
this.collection.bind('reset', this.addAllPlayers );
},
saveNewPlayer : function(event){
this.collection.create({
name : this.$form.find('input[name="name"]').val(),
});
}
});
(我省略了一些本示例不需要的代码)。
此代码正确保存新模型,将数据发送到服务器并创建与该新模型关联的 View 。
但我想知道在向服务器发送数据时如何处理服务器响应。
例如,如果服务器无法保存数据或发现任何其他类型的错误,我如何处理?
我是 Backbone 的新手,从现在开始我一直在使用 jQuery 来编写我的应用程序,所以我习惯使用 success
和 error
回调 $.ajax
优惠。
最佳答案
Backbone 提供类似的回调,作为第二个选项哈希添加到创建(以及获取和保存)命令中,如下所示:
this.collection.create({
name : this.$form.find('input[name="name"]').val(),
},{
error : function(model, response){},
success: function(model, response){}
});
关于javascript - Backbone : Handle server response on create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11890517/