Paul Hunt Paul Hunt - 9 days ago 5
jQuery Question

In Typescript how do I call a class method from another method in the same class that is called as an event handler

I have the following TypeScript code:

class MyClass {
constructor() {
$("#MyButton").on("click", this.MyCallback);
this.MyMethod();
}

MyCallback = () => {
$.ajax("http://MyAjaxUrl")
.done(function() {
this.MyMethod();
});
}

MyMethod = () => {
// Do some work
}
}


The problem I have is that when it reaches the JQuery ajax done function, it tells me that "MyMethod is not a function". Having debugged the Javascript I know that this is because "this" is not a reference to MyClass but I cannot work out how I can get a reference to the class at this point of execution.

Answer

Can it be solved by changing the code to:

$.ajax("http://MyAjaxUrl")
.done(() => {
    this.MyMethod();
});