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
},
this.buz.bind(this)or() => this.buz()bind