0

I'm using angular 7 with Pixi.js 4.

In order to get a click callback from a graphic element build with PIXI.Graphics() I need to set:

graphicElem.click = A_FUNCTION_REF

I have defined my function as a method inside my component:

onClick(event: PIXI.interaction.InteractionEvent): void { console.log(this.myCompField); }

If I write:

graphicElem.click = this.onClick;

I get from console log: undefined. I think because the this ref is not passed, but this is not true, I can log this and it is not undefined. Using this.onClick.bind(this); works but I read that the use of bind() is not recommended.

What is the correct way? What am I missing?

Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83
EduBic
  • 227
  • 4
  • 17

1 Answers1

1

You can use the Arrow Function Syntax instead of .bind in that case.

Try this:

onClick = (event: PIXI.interaction.InteractionEvent) => { console.log(this.myCompField); }
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
  • But I don't want to inline my function, I would want to use the method of my component class. – EduBic Nov 08 '18 at 13:57
  • @EduBic, any specific reason for that? Also, any specific reason for saying that the use of `.bind(this)` is not recommended? – SiddAjmera Nov 08 '18 at 13:59
  • [here](https://basarat.gitbooks.io/typescript/docs/tips/bind.html). Searching bind and angular I found this related [issue](https://stackoverflow.com/questions/45136680/how-to-properly-do-a-bind-in-angular2-typescript), maybe bind in this case is the only way to do that, or you can use an inline function as your suggestion. – EduBic Nov 08 '18 at 14:06
  • Yeap. BTW, bind is normally also used in case you define a custom validator. So saying that it's not recommended won't be correct. Why don't you want to do this the inline way BTW? – SiddAjmera Nov 08 '18 at 14:11
  • A function could grow in size. Anyway, your solution is the valid alternative, instance function preserves the correct this reference. This also brings to an issue of consistency between the methods declared in the component. – EduBic Nov 08 '18 at 14:14