将其他参数传递给事件处理程序 [英] Pass additional arguments to event handler?

查看:50
本文介绍了将其他参数传递给事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这样的对象中定义了我的函数:

i have my functions defined in an object like this:

_clickHandler: function(event){
  event.preventDefault();

},

attachClickEv: function(element){
  ......
  element.on('click', this._clickHandler);
},

问题是我似乎无法将this传递给clickHandler函数

the problem is that I cannot seem to pass "this" to the clickHandler function

我知道我可以将其包装在另一个函数中,例如

I know that I could wrap that in another function like

var tthis = this;
element.on('click', function(event){
  tthis._clickHandler(event, tthis);
});

但后来我不能用

element.off('click', this._clickHandler);

还有其他办法吗?

推荐答案

您可以使用bind。这是一个例子:

You can use bind for that. Here is an example:

element.on('click', this._clickHandler.bind(this));

//later in the code...

_clickHandler: function(event) {

}

既然你正在使用jQuery,你也可以使用 jQuery.proxy()太。更多信息: http://api.jquery.com/jQuery.proxy

Since you're using jQuery though, you can also use jQuery.proxy() too. More here: http://api.jquery.com/jQuery.proxy

更新

要访问回调中的元素,您必须使用 event.target event.currentTarget 或执行以下操作(取决于您正在做什么 ):

To get access to the element inside the callback you would have to use event.target or event.currentTarget or do the following (depends on what you're doing):

element.on('click', this._clickHandler.bind(this, element));

//later in the code...

_clickHandler: function(element, event) {

}

另一种方法是将元素设置为对象的属性,如: this.element = $(' #el')然后在你的回调中使用它。

Another way is to set the element as a property of the object like: this.element = $('#el') and then use that in your callback(s).

实例: http://jsbin.com/mezuberucu/1/edit?html,js,output

这篇关于将其他参数传递给事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆