Search code examples
jquerytypescriptcallbackclosuresecmascript-5

How to set classes's property in callback in TypeScript?


Here is what I am trying to do:

class User {

    name: string;

    userService: UserService; //service which fetches data from server

    successCallback(response: any) {
          this.name = string; 
    }

    setUser() {     
       var xhr: JQueryXHR = this.userService.fetchUser(); //Returns JQueryXHR object
       xhr.then(this.successCallback);
    }
}

Now, when I call setUser method on an instance of the User class:

var user: User = new User();
user.setUser(); 

this.name in successCallback evaluates to undefined

How can I get hold of the attribute of the class in callback function?


Solution

  • This is because the method is evaluated in windows context.

    Wrap the xhr.then call:

    xhr.then(response => {
        this.successCallback(response);
    });
    

    The => will make sure that this refers to the instance of this class.