我正在使用 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;
});
那么如何在表单中使用模型相关事件呢?