Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .each() function with ES6 arrow functions [duplicate]

I have this ES6 code, after I compile it with Babel to ES5 the this inside .each's call back becomes undefined. How do I fix this problem?

let mediaBoxes = $(".now-thumbnail"); let titles = []; mediaBoxes.each(() => {       let obj = {               index: i,               title: $(this).find(".now-thumbnail-bottomtext").text().trim()            };   titles.push(obj); }); 
like image 745
Tekeste Kidanu Avatar asked Apr 15 '16 03:04

Tekeste Kidanu


People also ask

Can I use arrow function in jQuery?

You can't. That's half the point of arrow functions, they close over this instead of having their own that's set by how they're called. For the use case in the question, if you want this set by jQuery when calling the handler, the handler would need to be a function function.

Does jQuery work with ES6?

jQuery source is now authored using ES6 modules. It's possible to use them directly in the browser without any build process.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

What is the difference between a normal function and an ES6 arrow function?

Since regular functions are constructible, they can be called using the new keyword. However, the arrow functions are only callable and not constructible, i.e arrow functions can never be used as constructor functions. Hence, they can never be invoked with the new keyword.


2 Answers

My solution is to not use this at all, but use the variables that are passed to the callback function. The first one is the index and the second one gives you the DOM element itself.

 let mediaBoxes = $(".now-thumbnail");  let titles = [];  mediaBoxes.each((index, element) => {                 let obj = {                     index: index,                     title: $(element).find(".now-thumbnail-bottomtext").text().trim()                 };                 titles.push(obj);  }); 
like image 155
Tekeste Kidanu Avatar answered Oct 03 '22 23:10

Tekeste Kidanu


That is because the mean of this is not the same in arrow functions.

this

Arrow functions capture the this value of the enclosing context,

The each() function passes the element as the second argument to the callback.

But a more appropriate solution for you will be to also use .map() instead of each()

let mediaBoxes = $(".now-thumbnail"); let titles = mediaBoxes.map((i, el) => {   return {     index: i,     title: $(el).find(".now-thumbnail-bottomtext").text().trim()   }; }).get(); 
like image 45
Arun P Johny Avatar answered Oct 04 '22 00:10

Arun P Johny