简体   繁体   English

BackboneJS:从视图提交表单时触发表单验证

[英]BackboneJS: Trigger form validation on form submit from view

So, I've started using Backbone.js to structure my javascript code and have modular applications, and I came across a problem reggarding events. 因此,我开始使用Backbone.js来构造我的javascript代码并拥有模块化的应用程序,并且遇到了一些有关重新生成事件的问题。

I want to make a simple View that handles forms and validates them. 我想制作一个简单的View,用于处理表单并验证它们。 In the future I would like to add all the javascript functionallity like live validation, hover effects, etc. 将来,我想添加所有JavaScript功能,例如实时验证,悬停效果等。

This is the simplified code I have right now: 这是我现在拥有的简化代码:

var Form = Backbone.View.extend({
    attributes: {
        att1 = 'att1',
        att2 = 'att2'
    },
    events: {
        'submit': 'validateFields'
    },
    initialize: function(element) {
        this.el = $(element);
    },
    validateFields: function() {
        alert(this.attributes.att1); //do something
        return false;
    }
});

var f = new Form('#formid');

The problem I had is that the validateFields function is not called when I submit the form. 我遇到的问题是,提交表单时未调用validateFields函数。 I also tried using this on the constructor: 我也尝试在构造函数上使用它:

this.el.bind('submit', this.validateFields);

Now, that last code works but the "this" inside the validation function would be the $('#formid') object, instead of my Form object. 现在,最后一个代码可以工作了,但是验证函数中的“ this”将是$('#formid')对象,而不是我的Form对象。

Backbone uses jQuery's delegate method to bind the events to the callbacks in the events hash. Backbone使用jQuery的delegate方法将事件绑定到events哈希中的回调。

Unfortunately the delegate method does not work for the submit event in IE See comment in Backbone source 不幸的是, delegate方法不适用于IE 中的Submit事件。 请参阅Backbone源中的注释。

An easy fix is to add this line of code to your render method. 一个简单的解决方法是将这行代码添加到render方法中。

render: function() {
  //render the view
  $(this.el).submit(this.validateFields);
}

You will also need to bind the context for validateFields in the initialize method 您还需要在initialize方法中为validateFields绑定上下文。

initialize: function() {
  _.bindAll(this, 'render', 'validateFields');
}

Try setting your el in other way: 尝试以其他方式设置您的el

var f = new Form({el: '#formid'});

In this case you can even remove initialize method (or change it): 在这种情况下,您甚至可以删除初始化方法(或更改它):

var Form = Backbone.View.extend({
    // ...
    initialize: function() {
        // Some code
    },
    // ...
});

As far as this code is concerned: this.el.bind('submit', this.validateFields); 就此代码而言: this.el.bind('submit', this.validateFields); . If you want to preserve Form object context you should use binding: 如果要保留Form对象上下文,则应使用绑定:

this.el.bind('submit', _.bind(this.validateFields, this)); // using Underscore method
this.el.bind('submit', $.proxy(this.validateFields, this)); // using jQuery method

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM