0

I'm trying to send class property as parameter to 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. 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;
}
Guy E
  • 1,775
  • 2
  • 27
  • 55
  • At least related: http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback – T.J. Crowder Oct 25 '17 at 08:12
  • @T.J.Crowder I guess it's full dupe. They appear every single day. – Estus Flask Oct 25 '17 at 09:17
  • @estus: I know; I close them. :-) To me it isn't quite because he/she isn't asking how to make `this` mean something particular in `XXXFunc`, but rather whether what he/she is doing above is okay or clunky. But I can see it both ways. – T.J. Crowder Oct 25 '17 at 09:24

1 Answers1

2

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:

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. So that will call XXXFunc with this referring to your instance, and this.activeTooltip will work within it.

There are other ways as well. In ES5 and earlier, you can use Function#call with a variable you close over:

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:

cancelDiv.addEventListener('click', () => XXXFunc.call(this));

In both cases, again, this in XXXFunc refers to your instance, so this.activeTooltip works.

And of course, if XXXFunc where a method on the instance, it would be even cleaner:

ES5- using Function#bind:

cancelDiv.addEventListener('click', this.XXXFunc.bind(this));

ES2015+ using an arrow function:

cancelDiv.addEventListener('click', () => this.XXXFunc());
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875