简体   繁体   English

TypeScript - 如何从事件处理程序方法访问类实例

[英]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.

相关问题 Angular 2和Typescript:无法从事件处理程序访问类实例 - Angular 2 & Typescript: Cannot access class instance from event handler 如何从传递给“ on”方法的事件处理程序访问“ $(this)”对象? - how to access to “$(this)” object from event handler passed to “on” method? 如何从TypeScript中的受保护方法访问私有实例变量 - How to access a private instance variable from a protected method in TypeScript 如何从typescript中的方法类中的函数访问类成员 - How to access class member from function in method class in typescript 如何从事件处理程序引用对象实例 - How to reference object instance from event handler 如何从JWPlayer实例中删除事件处理程序? - How to remove a event handler from JWPlayer instance? 如何将onlick事件处理程序作为类方法 - How to make an onlick event handler as a class method 如何将类方法设置为事件处理程序? - How to set the class method as event handler? 如何将事件处理程序定义为元素类方法? - How to define event handler as elements class method? 在事件处理程序中使用另一个类中的方法并绑定当前类上下文时,打字稿错误TS2339 - typescript error TS2339 when using method from another class in event handler and binding current class context
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM