Maverick
Maverick

Reputation: 4498

How to access Typescript module-level functions from within a jQuery event handler (without giving up the "normal" this)

Please forgive the wording, I wasn't quite sure how to word it (this also made it rather difficult to google for a solution).

Now, supposing the following Typescript:

module Foo {
    function Bar(elem: JQuery) {
        // Do something here.
    }

    function AddEventHandlers(): void {
        $(".className").click(function () {
            this.Bar($(this));  // I would like one of these 'this' to be not like the other.
        });
    }
}

What is the best way to accomplish this. I can think of two options myself (and these may have their own problems, please point them out if so), neither of which I particularly like:

$(".className").click((e) => {
    this.Bar($(e.currentTarget));  // Not sure if currentTarget will always be the right element?
});

Or:

var _this = this;
$(".className").click(function () {
    _this.Bar($(this));
});

Are these the only semi-decent ways to do this, or am I missing something?

Thanks in advance for the help! :).

EDIT: My first thought was actually that the following would have been acceptable:

$(".className").click(function () {
    Foo.Bar($(this));
});

But Typescript doesn't like that :(.

Upvotes: 1

Views: 128

Answers (1)

basarat
basarat

Reputation: 275849

Since you are using a module and not a class the following should suffice:

$(".className").click(function () {
    Bar($(this));
});

TypeScript automatically associates Bar with the closest scope (module Foo)

Upvotes: 1

Related Questions