如何将参数传递给事件处理函数并仍然使用'this'引用? [英] How to pass arguments to an event handler function and still use 'this' reference?

查看:86
本文介绍了如何将参数传递给事件处理函数并仍然使用'this'引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个情况(使用Raphael库),我有这个:

I have a situation (using the Raphael library) where I have this:

rect.click(doSomething);

doSomething()中,我可以得到边界框大小:

And within doSomething(), I can get the bounding box size:

var boxSize = this.getBBox();

问题是,如果我想将参数传递给doSomething怎么办?如果我这样做,那么这个引用会因某种原因而中断。我如何传递一个参数仍然使用这个

The problem is, what if I want to pass an argument to doSomething? If I do, then the this reference breaks for some reason. How can I pass in an argument and still use this?

推荐答案

您可以将侦听器包装在另一个函数中,并使用 .call() 使用给定参数调用函数:

You can wrap the listener in another function, and use .call() to call the function with given parameters:

var foo = 123, bar = 'blabla';
rect.click(function(event) {
    return doSomething.call(this, event, foo, bar);
});

这篇关于如何将参数传递给事件处理函数并仍然使用'this'引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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