airbnb / airbnb/javascript

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

Offen
#389 2 Kommentare 34 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen
editorial enhancement pull request wanted
Vorherrschende Sprache
JavaScript
Sterne
148k
Forks
26.6k
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

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?

Beitragsleitfaden

Für dieses Repository ist kein Beitragsleitfaden indexiert

Rechercherichtung

Das Issue behandelt jQuery-Ereignishandler, `$(this)`, `event.currentTarget` und Pfeilfunktionen, nennt jedoch keine Datei, keinen Test und keinen Einstiegspunkt im Repository. Bestimme zunächst, ob der Styleguide dies als schlechten Stil dokumentieren sollte, identifiziere dann den passenden Ort für die Anleitung und lege den erwarteten Wortlaut fest, bevor du eine Änderung vornimmst.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
javascript, jquery
Bereich
frontend
Issue-Typ
Dokumentation
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Muss geklärt werden
Anfängerfreundlichkeit
25/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.