How to manage "this" with TypeScript

Topics: General, Language Specification
Oct 17, 2012 at 4:00 PM
Edited Oct 17, 2012 at 4:00 PM

 

/// <reference path="jquery.d.ts" />
class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        $.ajax("Contact.html",{
            type: 'GET',
            dataType: 'html',
            success: function(response){
                this.greeting = response;

                //when i used with jquery.d.ts, this is list all the member of ajax interface.


            }
        })
    }
}  

 

How can i assing this.greeting to response. Thanks !

Oct 17, 2012 at 5:36 PM
Edited Oct 17, 2012 at 5:37 PM

If I remember correctly, use (response) => { } instead...

 

/// <reference path="jquery.d.ts" />
class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        $.ajax("Contact.html",{
            type: 'GET',
            dataType: 'html',
            success: (response) => {
                this.greeting = response;

                //when i used with jquery.d.ts, this is list all the member of ajax interface.


            }
        })
    }
}  

Oct 18, 2012 at 3:00 AM
Edited Oct 18, 2012 at 3:01 AM

Hi Please take a look at my picture.

You can see this in jquery ajax function is the this of ajaxsettings, what i want is access the this.Content to assign to response.

Please help me !

Oct 18, 2012 at 3:57 AM

I think this is just a bug... You're code is correect and this.Content should be accessible from within your function given you're using a lambda.  If you hover over this.Content it should say it's of type 'string' which means it figured it out it's just an intelisense bug that you're not getting Content in the list as yout type. I've seen this bug as well with Lambda's.

Try creating a "var _this = this;" variable outside your ajax call and use that in your callback. You may have better luck with the intellisense.  That's what they're going to generate for you anyway so it won't result an any larger JS then you would have already had.

Oct 19, 2012 at 1:16 AM

Thanks you for your reply, this is work now !