Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - How to access the class instance from event handler method

In the code snippet below, I have a TypeScript class and the instance method buz is the listener for canvas' click event.

this keyword in buz method refers to the event's target object(canvas).

How to get access to the foo instance from the buz method?

    class Foo {
        constructor(private _canvas: HTMLCanvasElement, private _message: string) {

        }

        public bar(): void {
            this._canvas.addEventListener(`click`, this.buz);
        }

        private buz(e: MouseEvent): void {
            console.info(`After click event, 'this' refers to canvas and not to the instance of Foo:`);
            console.info(this);
            console.warn(`Message is: "${this._message}"`); // error
        }
    }

    window.addEventListener('load', () => {
        let canvas = <HTMLCanvasElement> document.getElementById('canvas');
        let foo = new Foo(canvas, "Hello World");
        foo.bar();
    });

My tsconfig.json has these settings:

"compilerOptions": {
  "module": "commonjs",
  "target": "es5",
  "sourceMap": true
},
like image 549
Poulad Avatar asked Jun 17 '17 15:06

Poulad


People also ask

How do you bind an event handler to a class method in TypeScript?

In ES5, we can very easy bind a event to DOM using the native way: document. addEventListener() , or a jQuery way, $(element). bind() , $(element).

What can trigger execution of the event handler?

Event handler code can be made to run when an event is triggered by assigning it to the target element's corresponding onevent property, or by registering the handler as a listener for the element using the addEventListener() method.

What is addEventListener in TypeScript?

The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. Common targets are Element , or its children, Document , and Window , but the target may be any object that supports events (such as XMLHttpRequest ).


1 Answers

Your context is lost in the buz method when you pass it as a parameter. You can use arrow functions to achieve that. Arrow functions will save the context.

public bar(): void {
    this._canvas.addEventListener(`click`, (evt) => this.buz(evt));
}
like image 164
Suren Srapyan Avatar answered Oct 21 '22 20:10

Suren Srapyan