jQuery: $(this) vs $(event.currentTarget)
- Lingua principale
- JavaScript
- Stelle
- 148k
- Fork
- 26.6k
- Metriche di merge delle PR
- Nessuna PR unita negli ultimi 30g
Descrizione
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?
Guida per i contributori
Nessuna guida per i contributori indicizzata per questo repository
Direzione di ricerca
La issue riguarda i gestori di eventi jQuery, `$(this)`, `event.currentTarget` e le arrow function, ma non indica alcun file, test o punto di ingresso del repository. Determina innanzitutto se la guida di stile debba documentare questo comportamento come uno stile scorretto, quindi individua la posizione appropriata per le indicazioni e definisci la formulazione prevista prima di apportare qualsiasi modifica.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- javascript, jquery
- Ambito
- frontend
- Tipo di issue
- Documentazione
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Da chiarire
- Idoneità per principianti
- 25/100