gpt4 book ai didi

javascript - 如何在 submitHandler 回调中访问 Backbone View ?

转载 作者:行者123 更新时间:2023-11-30 18:25:52 25 4
gpt4 key购买 nike

我正在探索 backbone.js,我正在尝试设置简单的登录页面。这是我的 view.js 文件:

window.LoginView = Backbone.View.extend({   

events: {

},

initialize : function() {
this.model.bind("error", this.error);
this.template = _.template(tpl.get('login'));
},

login: function(form){
this.model.set({
login: $("#login", form).val(),
password: $("#password", form).val()
});
},

render : function(eventName) {
$(this.el).html(this.template());
$(this.el).find("form").validate({
submitHandler: this.login
});
return this;
}
});

如您所见,我在 render 函数中使用附加到表单的 jquery.validation。作为 submitHandler 回调,我设置了 login 函数。这条线

this.model.set({...

给我 this.model is undefined 错误所以我假设登录函数中的 this 中的 this 不同>initializerender 函数。我的问题是如何在登录功能中访问主干this

最佳答案

一种方法是使用 jQuery.proxy() 为登录函数设置“this”的值:

$(this.el).find("form").validate({
submitHandler: $.proxy(this.login, this)
});

Proxy 返回一个带有“this”新值的新函数。由于渲染函数中的“this”指向您的 View ,因此您将其作为第二个参数传递给代理。

关于javascript - 如何在 submitHandler 回调中访问 Backbone View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10862979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com