简体   繁体   中英

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.

I want to make a simple View that handles forms and validates them. In the future I would like to add all the javascript functionallity like live validation, hover effects, etc.

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. 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.

Backbone uses jQuery's delegate method to bind the events to the callbacks in the events hash.

Unfortunately the delegate method does not work for the submit event in IE See comment in Backbone source

An easy fix is to add this line of code to your render method.

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: function() {
  _.bindAll(this, 'render', 'validateFields');
}

Try setting your el in other way:

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); . If you want to preserve Form object context you should use binding:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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