3

If I'm inside a jQuery event, I'm not sure how I can access class variables. Example below

// <reference path="../typings/jquery/jquery.d.ts" />

export class Notes {

    // I want to access this inside of the click event
    test = "test";

    foo() {
        //works here
        alert(this.test);

        $("#testDiv").click(function () {

            // context of this changes so this no longer works
            alert(this.test);

            // How do I access the test variable in here?
        })
    }
}

2 Answers 2

7

If you use the lambda expression, it binds this to the enclosing scope's this.

export class Notes {
    private test: string = "test";

    foo() {
        //works here
        alert(this.test);

        $("#testDiv").click(() => {
            alert(this.test);
        })
    }
}

is translated into

var Notes = (function () {
    function Notes() {
        this.test = "test";
    }
    Notes.prototype.foo = function () {
        var _this = this;
        alert(this.test);
        $("#testDiv").click(function () {
            alert(_this.test);
        });
    };
    return Notes;
})();
exports.Notes = Notes;

Be careful however, inside the jQuery callback you will not be able to access the DOMElement as expected, since this is translated. If you want to be able to do both, add this to a variable in the closure yourself:

export class Notes {
    private test: string = "test";

    foo() {
        alert(this.test);
        var self = this;
        $("#testDiv").click(function() {
            alert(self.test);
            $(this).hide(); // still works
        })
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

I found a way that works however I feel like there is probably a better way?

export class Notes {
    test = "test";

    foo() {
        var self = this;

        $("#testDiv").click(function () {
            alert(self.test);
        })
    }
}

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.