Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialGerald Bishop
Python Development Techdegree Graduate 16,897 PointsShould arrow functions work with the "this" keyword in jQuery?
The code on lines 25 to 27 of app.js
do not seem to work with the this
keyword:
I can only get it to work if I change the ()=> arrow function to a function declaration, i.e., using the function keyword or by changing the this
keyword to event.target
and inserting event
as a parameter.
Can I change my code to get the arrow function to work with the this
keyword?
Thanks
Gerald Bishop
Python Development Techdegree Graduate 16,897 Pointsjosephweiss2 sorry I accidentally deleted the snapshot. Here is the code that doesn't work:
$('ul').on('dblclick', 'li', ()=> {
$(this).toggleClass("strike");
});
As Steven says, the ()=> needs to be changed to function()
for it to work with the this
keyword.
Steven Parker
231,248 PointsThis is a better solution than converting the function so you can use "this":
$('ul').on('dblclick', 'li', e => {
$(e.target).toggleClass("strike");
});
1 Answer
Steven Parker
231,248 PointsThis is not related to jQuery. Arrow functions just don't bind "this" like conventional functions do. For more details, see this MDN page on Arrow function expressions.
But for event handlers, passing the event object to a parameter is the "best practice" approach anyway.
josephweiss2
7,094 Pointsjosephweiss2
7,094 Pointsthe link doesn't work, can you Passover your code? that will make it better to see what's the problem. Thanks