0

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.

Paul Hunt
  • 3,395
  • 2
  • 24
  • 39
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – artem Dec 01 '16 at 08:31

1 Answers1

2

Can it be solved by changing the code to:

$.ajax("http://MyAjaxUrl")
.done(() => {
    this.MyMethod();
});
Chiu
  • 374
  • 2
  • 10