-
Notifications
You must be signed in to change notification settings - Fork 26.8k
Open
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:
// 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?
n3nad, aristotll, isaachvazquez, sephie, allanchau and 23 moresteve-holland, JohnnyMa, kabrice and 3zoWebDevkabrice and 3zoWebDev