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?

3 Answers 3

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);
});
Sign up to request clarification or add additional context in comments.

4 Comments

This is one of my favourite things about Typescript.
This could be much more clear if data was used in this example too
@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.
@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. stackoverflow.com/questions/37362178/…
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..
        });
    }
}

3 Comments

Aha.. my lack of javascript skills
While this is technically correct, using arrow functions is the better way to do this.
This techinque works for other similar scenarios. Was a pointer in the right direction for me.
1

Fenton is right.

But you can also do this:

 mycallback(todos, self) { self.todo(todos)); }
 $.get('url', mycallback(todos, this));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.