1

我正在使用 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;
});

那么如何在表单中使用模型相关事件呢?

4

1 回答 1

4

这些事件不是 DOM 事件,而是 Backbone 事件validated:valid。events 哈希用于处理 DOM 事件(source),而用于点击特定模型触发的事件validated:invalidBackbone.Viewmodel.bind

所以从事件哈希中删除这些行:

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
}

现在您正在以正确的方式利用模型事件。

希望这可以帮助!

于 2012-07-09T15:28:14.497 回答