Skip to content

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

Open
@winterbe

Description

@winterbe

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?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions