[英]javascript - pass reference of class property to addEventListener
I'm trying to send class property as parameter to addEventListener. 我正在尝试将类属性作为参数发送给addEventListener。 Doing this is because when the event occurs, I'm no longer in the context of the class (this) and can't get\\set the value of the property.
这样做是因为当事件发生时,我不再处于类(this)的上下文中,并且无法获取\\设置属性的值。 I need somehow pass a reference of the property to the function.
我需要以某种方式将属性的引用传递给函数。 I'm aware that I can add the property as attribute to the event target and reach it like this, but I quite sure that there should be a more straight forward solution.
我知道我可以将属性作为属性添加到事件目标,并以这种方式到达它,但我很确定应该有一个更直接的解决方案。 This is the relevant code:
这是相关代码:
export class ZZZZZ{
constructor()
{
this.activeTooltip = null; //This is the relevant property
}
YYYYFunc()
{
/*thinking of doing it like that*/
var activeTooltip = this.activeTooltip;
cancelDiv.addEventListener('click', function() { XXXFunc(activeTooltip)});
}
XXXFunc(activeTooltip)
{
var A = this.activeTooltip; //I'm not in the context of the class -
//"this" is irrelevant - it is null
var B = activeTooltip;
}
The way you're doing it works and is fairly common, but note that there's no reason you can't make this
in XXXFunc
your instance, by using Function#bind
: 你正在做的事情是这样的工作原理,是相当常见的,但要注意,没有理由你不能让
this
在XXXFunc
您的实例,通过使用Function#bind
:
cancelDiv.addEventListener('click', XXXFunc.bind(this));
bind
returns a new function that, when called, will call the original with this
set to the value you give bind
. bind
返回一个新的函数,调用它时,会调用原来与this
设置为您提供的值bind
。 So that will call XXXFunc
with this
referring to your instance, and this.activeTooltip
will work within it. 因此,将调用
XXXFunc
与this
指的是您的实例,并this.activeTooltip
将在它的工作。
There are other ways as well. 还有其他方法。 In ES5 and earlier, you can use
Function#call
with a variable you close over: 在ES5和更早版本中,可以对关闭的变量使用
Function#call
:
var _this = this;
cancelDiv.addEventListener('click', function() { XXXFunc.call(_this)});
In ES2015+, you can use an arrow function instead of the variable, since the arrow function closes over this
itself: 在ES2015 +,你可以用一个箭头的功能而不是变量,由于箭头功能关闭了
this
本身:
cancelDiv.addEventListener('click', () => XXXFunc.call(this));
In both cases, again, this
in XXXFunc
refers to your instance, so this.activeTooltip
works. 在这两种情况下,再次,
this
在XXXFunc
是指你的实例,因此this.activeTooltip
工作。
And of course, if XXXFunc
where a method on the instance, it would be even cleaner: 当然,如果
XXXFunc
在实例上有方法,它将更加干净:
ES5- using Function#bind
: ES5-使用
Function#bind
:
cancelDiv.addEventListener('click', this.XXXFunc.bind(this));
ES2015+ using an arrow function: ES2015 +使用箭头功能:
cancelDiv.addEventListener('click', () => this.XXXFunc());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.