如何在jquery中的click事件的处理程序中获取对象的this?
// begin signals this.loginSignal this.init = function(){ // init signals this.loginSignal = new t.store.helpers.Signal; // map events $('[value]="login"', this.node).click(this.login) } this.login = function(){ // this will dispatch an event that will be catched by the controller // but this is not refering to this class // and the next line fails :s this.loginSignal.dispatch(); }
为了让它工作,我必须添加
var $this = this;
这一行并使用$this
而不是:S
更清楚的方式? 谢谢
调用单击处理程序时, this
关键字将重新映射到触发事件的元素。 要获取原始对象,您需要将函数代码放在闭包中,并在闭包外部引用对象,在此处您仍然可以正确引用this
。
// map events var thisObject = this; $('[value]="login"', this.node).click(function () { thisObject.loginSignal.dispatch(); });
技巧1:使用闭包
var me = this; $(...).click(function(){ me.login(); });
技巧2:获取处理事件的元素
this.login = function(evt){ var el = evt.currentTarget || evt.target || evt.srcElement; // Do something with the element here. };
jQuery有一个名为jQuery.proxy()
的方法,用于返回一个函数,该函数的值设置为你想要的值。
$('[value="login"]', this.node).click( $.proxy(login, this) );