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
},
In ES5, we can very easy bind a event to DOM using the native way: document. addEventListener() , or a jQuery way, $(element). bind() , $(element).
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.
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 ).
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With