我正在使用thedersen的Backbone.validation插件来提供验证。
验证本身到目前为止工作并在我提交表单时执行。关于让视图监听验证错误,我只是没有成功。
howto表示您可以通过以下方式收听验证事件:
model.bind('validated:invalid', function(model, attrs) {
// do something
});
来源:http://thedersen.com/backbone.validation/#events/validated
define(['jquery', 'underscore', 'backbone', "models/security/user", 'text!templates/security/registration.html'], function($, _, Backbone, SecurityUserModel, Template){
var SecurityRegistrationView;
SecurityRegistrationView = Backbone.View.extend({
initialize: function(){
this.model = new SecurityUserModel();
this.render();
Backbone.Validation.bind(this);
},
render: function(){
$(this.el).append(Template);
},
events: {
"submit form": "submit"
, "validated:valid": "valid"
, "validated:invalid": "invalid"
},
submit: function(e){
e.preventDefault();
var username, email, password;
username = $("#_user_username").val();
email = $("#_user_email").val();
password = $("#_user_password").val();
this.model.set('username', username);
this.model.set('email', email);
this.model.set('password', password);
this.model.validate();
console.log(this.model.validate());
},
invalid: function(){
$("input").addClass("inputError");
alert(" ");
},
valid: function(){
alert(" ");
this.model.save(function(){
// server validation callback...
});
}
});
return SecurityRegistrationView;
});
那么如何在表单中使用模型相关事件?
答案 0 :(得分:4)
事件validated:valid
和validated:invalid
不是DOM事件,而是Backbone事件。 Backbone.View
事件哈希用于处理DOM事件(source),而model.bind
用于利用特定模型触发的事件。
所以从events-hash中删除这些行:
events: {
"submit form": "submit", // LEAVE THIS AS IT IS A DOM EVENT
"validated:valid": "valid", // REMOVE THIS
"validated:invalid": "invalid" // REMOVE THIS
}
并将其添加到初始化函数
initialize: function(){
this.model = new SecurityUserModel();
this.render();
Backbone.Validation.bind(this);
this.model.bind('validated:valid', this.valid); // NEW
this.model.bind('validated:invalid', this.invalid); // NEW
}
现在你正在以正确的方式进入模型事件。
希望这有帮助!