3

In Javascript the following code works as expected:

$("#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.

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

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

gives me an error because "invokeClassMethod" is undefined.

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
riqitang
  • 3,241
  • 4
  • 37
  • 47

1 Answers1

5

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:

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

using bind() also works:

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

and jQuery proxy works:

$("#field").click($.proxy(this.eventHandler, this));
riqitang
  • 3,241
  • 4
  • 37
  • 47