BackboneJS:从视图提交表单时触发表单验证
因此,我开始使用 Backbone.js 来构建我的 javascript 代码并拥有模块化应用程序,但我遇到了有关事件的问题。
我想制作一个简单的视图来处理表单并验证它们。将来我想添加所有 javascript 功能,如实时验证、悬停效果等。
这是我现在拥有的简化代码:
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');
我遇到的问题是,当我提交表单时,不会调用 validateFields 函数。我还尝试在构造函数上使用 this :
this.el.bind('submit', this.validateFields);
现在,最后一个代码可以工作,但验证函数内的“this”将是 $('#formid') 对象,而不是我的 Form 对象。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Backbone 使用 jQuery 的
delegate
方法将事件绑定到events
哈希中的回调。不幸的是,
delegate
方法不适用于 IE 查看 Backbone 源代码中的注释一个简单的修复方法是将这行代码添加到您的
render
方法中。您还需要在初始化方法中绑定 validateFields 的上下文
Backbone uses jQuery's
delegate
method to bind the events to the callbacks in theevents
hash.Unfortunately the
delegate
method does not work for the submit event in IE See comment in Backbone sourceAn easy fix is to add this line of code to your
render
method.You will also need to bind the context for validateFields in the initialize method
尝试以其他方式设置您的
el
:在这种情况下,您甚至可以删除初始化方法(或更改它):
就这段代码而言:
this.el.bind('submit' , this.validateFields);
。如果你想保留 Form 对象上下文,你应该使用绑定:Try setting your
el
in other way:In this case you can even remove initialize method (or change it):
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: