Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access class member from function in method class in typescript

Tags:

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?

like image 895
Flores Avatar asked Nov 17 '12 13:11

Flores


2 Answers

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); }); 
like image 62
Fenton Avatar answered Sep 30 '22 22:09

Fenton


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..         });     } } 
like image 37
Jakub Konecki Avatar answered Sep 30 '22 22:09

Jakub Konecki