[英]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. 在下面的代码片段,我有一个打字稿类和实例方法
buz
是画布监听click
事件。
this
keyword in buz
method refers to the event's target object(canvas). buz
方法中的this
关键字是指事件的目标对象(canvas)。
How to get access to the foo
instance from the buz
method? 如何从
buz
方法访问foo
实例?
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: 我的
tsconfig.json
有以下设置:
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"sourceMap": true
},
Your context is lost in the buz
method when you pass it as a parameter. 当您将其作为参数传递时,您的上下文在
buz
方法中丢失。 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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.