Reputation: 699
I need to get a href value after click. My code looks like this:
$('.menu a').click (event) =>
event.preventDefault()
console.log($(this).attr('href')) # it returns 'undefined'
What am I doing wrong?
[edited]
My html code:
<div class="menu">
<a href="/all/">All</a>
</div>
Upvotes: 1
Views: 39
Reputation: 20554
This is because of the subtle difference in Coffeescript between =>
and ->
In JavaScript, the this keyword is dynamically scoped to mean the object that the current function is attached to. If you pass a function as a callback or attach it to a different object, the original value of this will be lost. If you're not familiar with this behavior, this Digital Web article gives a good overview of the quirks.
The fat arrow => can be used to both define a function, and to bind it to the current value of this, right on the spot. This is helpful when using callback-based libraries like Prototype or jQuery, for creating iterator functions to pass to each, or event-handler functions to use with bind. Functions created with the fat arrow are able to access properties of the this where they're defined.
This is why this
is binded to window.
You should use:
$('.menu a').click (event) ->
event.preventDefault()
console.log($(this).attr('href')) # it returns the link !
Upvotes: 2