Is there an alias for 'this' in TypeScript?

Posted by Todd on Stack Overflow See other posts from Stack Overflow or by Todd
Published on 2012-10-06T03:26:15Z Indexed on 2012/10/06 3:37 UTC
Read the original article Hit count: 167

Filed under:
|

I've attempted to write a class in TypeScript that has a method defined which acts as an event handler callback to a jQuery event.

class Editor {
    textarea: JQuery;

    constructor(public id: string) {
        this.textarea = $(id);
        this.textarea.focusin(onFocusIn);
    }

    onFocusIn(e: JQueryEventObject) {
        var height = this.textarea.css('height'); // <-- This is not good.
    }
}

Within the onFocusIn event handler, TypeScript sees 'this' as being the 'this' of the class. However, jQuery overrides the this reference and sets it to the DOM object associated with the event.

One alternative is to define a lambda within the constructor as the event handler, in which case TypeScript creates a sort of closure with a hidden _this alias.

class Editor {
    textarea: JQuery;

    constructor(public id: string) {
        this.textarea = $(id);
        this.textarea.focusin((e) => {
            var height = this.textarea.css('height'); // <-- This is good.
        });
    }
}

My question is, is there another way to access the this reference within the method-based event handler using TypeScript, to overcome this jQuery behavior?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about TypeScript