piernik
piernik

Reputation: 3657

jQuery click event with fat-arrow function

Using jQuery's click event with fat arrow function can be confusing. Event.target is not what You expect. Here is code sample:

constructor() {
    $("a.nav-link").click((e)=>{
        this.func($(e.target).data("target"));
    })
}

private func(target: string) {
    console.log(target);
}

<a class="nav-link" data-target="search"><i class="fa fa-search"></i></a>

Some times event.target is i element - not expected a tag.

I have workaround:

constructor() {
    let _this = this;
    $("a.nav-link").click(function (e) {
        _this.func($(this).data("target"));
    })
}

Is there a solution working with fat arrow function?

Upvotes: 2

Views: 1965

Answers (1)

Eliran Malka
Eliran Malka

Reputation: 16263

You can't get away with the first implementation - one of the stated capabilities of the arrow function syntax is the lexical binding of this, so this is not what you expect here, as you override jQuery's handler function this binding.
This matters as instead of using e.target you'll be better off with $(this) (but you won't be able to get the right this for your purposes - you need this to point at your class instance).

That said, there is no relation to the event parameter's properties. It's passed as-is regardless of the function context.

Your "workaround" has two parts: using a function statement, and retrieving the bound element via $(this). The later is actually the proper way of dealing with your issue, and the former allows you to refer to both contexts inside the function.

Its a perfectly valid solution, I say go with it, and don't try to force a solution with arrow functions where they don't fit.

Upvotes: 5

Related Questions