airbnb / airbnb/javascript

jQuery: $(this) vs $(event.currentTarget)

Open
#389 2 comments 34 reactions 0 assignees View on GitHub
editorial enhancement pull request wanted
Dominant language
JavaScript
Stars
148k
Forks
26.6k
PR merge metrics
No merged PRs in 30d

Description

When working with jQuery in ES6 you have to pay particular attention to `$(this)` in event handlers. Using `$(this)` in ES5 is quite popular to access the DOM element of the event handler. In ES6 the code breaks if you switch from function to arrow function syntax:

``` js
// works:
$selector.on('click', function() {
$(this).hide();
});

// doesn't work:
$selector.on('click', () => $(this).hide());
```

Instead you have to access the DOM element via `event.currentTarget`:

``` js
// works:
$selector.on('click', ev => $(ev.currentTarget).hide());
```

IMO the main problem is that you can accidentally break code by just switching from `function` syntax to arrow functions. I'm aware that this problem is not exclusive to jQuery but since `$(this)` is so widely used in jQuery code, imo it wouldn't be the badest idea idea to add this to the list of bad styles.

What do you think?

Contributor guide

No contributing guide indexed for this repository

Research direction

The issue discusses jQuery event handlers, `$(this)`, `event.currentTarget`, and arrow functions, but names no repository file, test, or entry point. First determine whether the style guide should document this as a bad style, then identify the appropriate guidance location and define the expected wording before making any change.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, jquery
Domain
frontend
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.