Backbone1.0.0数据验证的变化
0.5.3版本对Model数据验证时,绑定Error就可以了:
(function(){ var Model = Backbone.Model.extend({ initialize : function(){ this.bind('error',function(model,error){ alert(error); }); }, validate : function(attrs){ for (var key in attrs){ if (attrs[key] == ''){ return key + '不能为空'; } } } }); var model = new Model; model.set({name:''}); model.set({age:''}); })();
1.0.0版本有变化,需要绑定invalid事件,而且要显示声明{validate:true}:
(function(){ var Model = Backbone.Model.extend({ initialize : function(){ this.bind('invalid',function(model,error){ alert(error); }); }, validate : function(attrs){ for (var key in attrs){ if (attrs[key] == ''){ return key + '不能为空'; } } } }); var model = new Model; model.set({name:''},{validate:true}); model.set({age:''},{validate:true}); })();
Backbone的例子网上比较少,文档不多,如果突然使用新版文件可能难以找出问题。