我有一个处理注册组件的主干 View ,因为这需要大量的表单访问,所以我想到了将表单选择器存储在对象属性中。
define(["models/security/user", 'text!templates/security/registration.html'], function(SecurityUserModel, Template){
var SecurityRegistrationView;
SecurityRegistrationView = Backbone.View.extend({
initialize: function(){
this.model = new SecurityUserModel();
this.model.bind("validated:valid", this.valid);
this.model.bind("validated:invalid", this.invalid);
Backbone.Validation.bind(this);
this.render();
},
render: function(){
$(this.el).append(Template);
},
events: {
"submit form": "submit"
},
form: {
"username": $("#_user_username")
, "email": $("#_user_email")
, "password": $("#_user_password")
},
submit: function(e){
e.preventDefault();
this.model.set("username", this.form.username.val());
this.model.set("password", this.form.email.val());
this.model.set("email", this.form.password.val());
this.model.validate();
// debug
console.log([this.form, this.form.username.val(), this.form.email.val()]);
if (this.model.isValid) {
this.model.save();
}
},
valid: function(model, attrs){
// error
this.form.attrs[0].username.parent("div.control-group").addClass("success");
},
invalid: function(model, attrs){
// error
this.form.attrs[0].username.parent("div.control-group").addClass("error");
}
});
return SecurityRegistrationView;
});
当我对 this.form 进行控制台记录时,我得到一个看起来相当不错的对象,没有未定义或奇怪的东西:
[
Object
email: e.fn.e.init[0]
context: HTMLDocument
selector: "#_user_email"
__proto__: Object[0]
password: e.fn.e.init[0]
context: HTMLDocument
selector: "#_user_password"
__proto__: Object[0]
username: e.fn.e.init[0]
context: HTMLDocument
selector: "#_user_username"
__proto__: Object[0]
__proto__: Object
]
登录一个访问选择器的 jquery 函数 (this.form.username.val()) 失败并显示未定义。
为什么不能在属性上使用jQuery函数($el uses this to)思维错误在哪里?
最佳答案
我认为问题在于,form: {...}
在 render
被调用之前被评估——并且您查询的 HTML 元素是在 中创建的渲染
。
也许您可以尝试在渲染函数的最后执行此操作:
this.form = {
"username": $("#_user_username")
, "email": $("#_user_email")
, "password": $("#_user_password")
}
关于javascript - Backbone View 无法访问 jQuery 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11400523/