Home > Web Front-end > JS Tutorial > How to Correctly Use jQuery's $(this) with ES6 Arrow Functions in Event Handlers?

How to Correctly Use jQuery's $(this) with ES6 Arrow Functions in Event Handlers?

Mary-Kate Olsen
Release: 2024-12-14 06:15:12
Original
384 people have browsed it

How to Correctly Use jQuery's $(this) with ES6 Arrow Functions in Event Handlers?

Using jQuery $(this) with ES6 Arrow Functions (lexical this binding)

Binding event handlers using ES6 arrow functions can be problematic when working with jQuery's $(this) selector. This is because arrow functions bind the this keyword lexically, which may not be the desired behavior in jQuery callbacks.

The following example illustrates the issue:

class Game {
  foo() {
    this._pads.on('click', () => {
      if (this.go) { $(this).addClass('active'); }
    });
  }
}
Copy after login

In the above example, using an arrow function for the click event handler results in $(this) referencing the Game instance instead of the clicked element. This is because arrow functions do not have their own this binding, so they inherit it from the surrounding scope.

Solution

To resolve this issue, avoid using arrow functions when binding jQuery event handlers. Instead, use traditional function declarations or bind the this keyword explicitly using the bind method:

class Game {
  foo() {
    this._pads.on('click', function() {
      if (this.go) { $(this).addClass('active'); }
    }.bind(this));
  }
}
Copy after login

Alternatively, you can access the clicked element using event.currentTarget:

class Game {
  foo() {
    this._pads.on('click', (event) => {
      if (this.go) { $(event.currentTarget).addClass('active'); }
    });
  }
}
Copy after login

Using event.currentTarget provides access to the element that triggered the event, regardless of the binding context of the callback function.

The above is the detailed content of How to Correctly Use jQuery's $(this) with ES6 Arrow Functions in Event Handlers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template