13

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
},
3
  • this.buz.bind(this) or () => this.buz() Commented Jun 17, 2017 at 15:44
  • 1
    Possible duplicate of The value of "this" within the handler using addEventListener Commented Jun 17, 2017 at 15:46
  • @AndrewLi Very similar to that but this one is using TS and its arrow functions. No need for bind Commented Jun 17, 2017 at 15:51

1 Answer 1

29

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));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I changed my method call to this: this._canvas.addEventListener('click', evt => this.buz(evt));
you save my day

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.