Angular + PIXI - How to assign a component method to a variable and preserve 'this' reference

3766 views angular
2

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?

answered question

1 Answer

9

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

Try this:

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

posted this

Have an answer?

JD

Please login first before posting an answer.