0.5.3版本對Model數據驗證時,綁定Error就能夠了:this
(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}:spa
(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的例子網上比較少,文檔很少,若是忽然使用新版文件可能難以找出問題。code