Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
winterbe opened this issue Jul 3, 2015 · 2 comments
Open

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

winterbe opened this issue Jul 3, 2015 · 2 comments

Comments

@winterbe
Copy link
Contributor

winterbe commented Jul 3, 2015

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:

// 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:

// 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?

@goatslacker
Copy link
Collaborator

If you need to use this then using a function is acceptable.

@PocketNinjaDesign
Copy link

Just started using the Airbnb eslint setup and though I'm not to bothered about using e.currentTarget I am most certainly bothered that I have to override the airbnb lint for call apply and calling jquery functions that require this for chaining. I guess that is one reason why the comment wrappers were introduced to say leave this area alone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants