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?

0

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.