Recently, I delved into using Backbone.js to organize my JavaScript code and create modular applications. However, I encountered a snag when dealing with events.
My goal is to develop a simple View that can handle forms and validate them. Eventually, I plan to integrate additional JavaScript functionality like live validation and hover effects.
Here is the basic code snippet I currently have:
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 issue I encountered is that the validateFields function is not triggered when I submit the form. I attempted to bind the event in the constructor as follows:
this.el.bind('submit', this.validateFields);
Although the above code works, the "this" within the validateFields function refers to the $('#formid') object rather than my Form object.