TypeScript 单击事件处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33745006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:08:01  来源:igfitidea点击:

TypeScript click event handler

javascript-eventstypescript

提问by riqitang

In Javascript the following code works as expected:

在 Javascript 中,以下代码按预期工作:

$("#field").click(eventHandler);

function eventHander() {
  invokeClassMethod();
  // do other stuff
}

I tried this in Typescript and I get an error because it appears the context of "this" has changed to something that's not my class.

我在 Typescript 中尝试过这个,但出现错误,因为“this”的上下文似乎已更改为不是我的类的内容。

$("#field").click(this.eventHandler);

eventHandler() {
  this.invokeClassMethod();
  // do other stuff
}

gives me an error because "invokeClassMethod" is undefined.

给我一个错误,因为“invokeClassMethod”未定义。

I'm new to Typescript so can somebody please tell me what's wrong and how to fix it?

我是 Typescript 的新手,所以有人可以告诉我有什么问题以及如何解决吗?

回答by riqitang

Ah ok the answer was simple and really comes down to me being unfamiliar with Javascript features... here's how I got it to work:

嗯,答案很简单,归根结底是我不熟悉 Javascript 功能……这是我如何让它工作的:

$("#field").click(() => this.eventHandler());

using bind() also works:

使用 bind() 也有效:

$("#field").click(this.eventHandler.bind(this));

and jQuery proxy works:

和 jQuery 代理工作:

$("#field").click($.proxy(this.eventHandler, this));