22

I have this typescript code:

    module MyPage {

    export class MyVm {

        ToDo : string;

        Load() {
            //can access todo here by using this:
            this.ToDo = "test";

            $.get("GetUrl", function (servertodos) {
                //but how do I get to Todo here??
                this.ToDo(servertodos); //WRONG ToDo..
            });
        }
    }
}

The question is, how do I access the todo member field in the $.get callback?

Flores
  • 8,226
  • 5
  • 49
  • 81

3 Answers3

31

TypeScript also supports arrow function that preserve lexical scoping. Arrow functions result in similar code to Jakub's example but are neater as you don't need to create the variable and adjust usage yourself:

Here is the example using an arrow function:

$.get("GetUrl", (todos) => {
    this.ToDo(todos);
});
Fenton
  • 241,084
  • 71
  • 387
  • 401
  • 3
    This is one of my favourite things about Typescript. – Maverick Jun 25 '14 at 04:50
  • This could be much more clear if `data` was used in this example too – Serj Sagan Oct 08 '15 at 21:41
  • @SerjSagan in the original question, the `data` parameter was named `todos` as this is the kind of data that is being supplied by the call. You can use `data` in place of `todos` in the above example if you wish. The `todos` parameter would contain the data object that jQuery passes to the callback. – Fenton Oct 09 '15 at 18:04
  • @Sohnee 'this' does not work for me as shown above. Please refer to the question link and correct me if I am doing something wrong. http://stackoverflow.com/questions/37362178/this-scope-in-typescript-callback-function – Microsoft Developer May 21 '16 at 11:13
13

The same way you do it in javascript

export class MyVm {
    ToDo : string;

    Load() {
        //can access todo here by using this:
        this.ToDo = "test";
        var me = this;

        $.get("GetUrl", function (todos) {
            //but how do I get to Todo here??
            me.ToDo(todos); //WRONG ToDo..
        });
    }
}
Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
1

Fenton is right.

But you can also do this:

 mycallback(todos, self) { self.todo(todos)); }
 $.get('url', mycallback(todos, this));
NaN
  • 8,596
  • 20
  • 79
  • 153