Paul Hunt
Paul Hunt

Reputation: 3555

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.

Upvotes: 0

Views: 488

Answers (1)

Chiu
Chiu

Reputation: 374

Can it be solved by changing the code to:

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

Upvotes: 2

Related Questions