jQuery and ES6 arrow functions
The basic functionality is trivial: The Event
object the handler receives has a currentTarget
property which is the same as this
:
$(".all-buttons").click(e => console.log(e.currentTarget.innerHTML));
Note this is not the same as e.target
:
target
is the element the event is targeted at, whereascurrentTarget
is the element the event is passing through on en route to that target on which this handler was hooked
So for instance, if you have
<div>
<span>click me</span>
</div>
...and you have a handler hooked to that div
, clicking the span
will give you e.target
= the span
, e.currentTarget
= the div
.
Regarding "other libraries," library recommendations are off-topic for SO. But I'll note that on modern browsers:
- The
NodeList
returned by the DOM's ownquerySelectorAll
hasforEach
, which makes it easy to loop over matches (it's also trivial to polyfill on any vaguely-recent browser) - DOM elements also now have a
closest
method which makes event delegation with the DOM much simpler than it used to be (and again, can be polyfilled).
Jquery with arrow function
from https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
An arrow function expression has a shorter syntax than a function
expression and does not bind its own this, arguments, super, or
new.target. These function expressions are best suited for non-method
functions, and they cannot be used as constructors.
ES6 Arrow functions vs ES5: how to know which function to bind `this` to when using ES5 non-arrow function
Why do you use
bind(this)
with the callback tosetTimeout
rather than with the counter function?
Because the counter
function (which works like a method of the obj
object) already has the proper this
because you call it like obj.counter()
so it gets this
from calling it as obj.counter()
. Assuming you call counter as obj.counter()
, then if you do console.log(this.id)
on the first line of the counter()
function, it will properly show the id
value.
The callback you pass to setTimeout()
however has no natural this
value unless you use an arrow function or .bind()
on the callback function itself because when setTimeout()
calls your callback it does not set a specific this
value (it just calls your callback as a normal function), therefore the this
value goes to the default. That means this
will be undefined
if running strict mode or the global object if running in loosey-goosey mode inside of the setTimeout()
callback.
See the 6 ways that the value of this
is set here when calling a function.
I should also mention that if you did what you were proposing like this:
var obj = {
id: 42,
counter: function counter() {
setTimeout(function() {
console.log(this.id);
}, 1000);
}.bind(this);
};
Not only would it not help the setTimeout()
callback at all, but it would also bind the wrong value of this
to the counter()
method. You would get whatever this
was before the var obj
definition (also known as the lexical value of this
).
What does this refer to in arrow functions in ES6?
Arrow functions capture the this
value of the enclosing context
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this| properly refers to the person object
}, 1000);
}
var p = new Person();
So, to directly answer your question, this
inside your arrow function would have the same value as it did right before the arrow function was assigned.
Using the this keyword to itterate through a jquery Selector
Don't use an arrow function. They don't re-bind this
.
Instead, the this
of the enclosing lexical scope is used.
$("#submit").click(e => {
e.preventDefault();
let inputs = $("input");
inputs.each(function(){
console.log($(this).val());
});
});
Should work just fine.
More information on arrow functions and the behaviour of this
:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
How to get the element from a jQuery on() event using an ES6 arrow function?
You can use event.currentTarget to refer to the target element of the handler
$(document).on('click', '.inserted-el', function(event) {
snippet.log('old -> ' + this.innerHTML + ':' + event.currentTarget.innerHTML);
});
$(document).on('click', '.inserted-el', (event) => {
snippet.log('new -> ' + this.innerHTML + ':' + event.currentTarget.innerHTML);
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="inserted-el">1</button>
<button class="inserted-el">2</button>
Related Topics
Do You Recommend Using Semicolons After Every Statement in JavaScript
Find the Min/Max Element of an Array in JavaScript
Correct Modification of State Arrays in React.Js
Convert String to Title Case With JavaScript
Difference Between Call and Apply
Chrome Extension Message Passing: Response Not Sent
Events Triggered by Dynamically Generated Element Are Not Captured by Event Handler
When Should I Use Arrow Functions in Ecmascript 6
How to Use Unicode-Aware Regular Expressions in JavaScript
What Does "Use Strict" Do in JavaScript, and What Is the Reasoning Behind It
JavaScript: Natural Sort of Alphanumerical Strings
Resolve Promises One After Another (I.E. in Sequence)
How to Use Formdata For Ajax File Upload