I have a coffeescript class that has some jquery event listeners. I would like to use the fat arrow =>
to avoid having to reference the class, but I still need a reference to the element that would usually be used with this
. How can I use both?
class PostForm
constructor: ->
$('ul.tabs li').on 'click', =>
tab = $(this)
@highlight_tab(tab)
@set_post_type(tab.attr('data-id'))
highlight_tab: (tab)->
tab.addClass 'active'
set_post_type: (id) ->
$('#post_type_id').val(id)
I prefer this version, because I can understand it more easily.
CoffeeScript links both
this
and@
to the outer context, therefore you cannot access the context that jQuery provided (aka the desired "this"). Useevent.target
instead:Using evt.currentTarget
You should probably use
evt.currentTarget
(which is equivalent tothis
) instead ofevt.target
(which isn't). If the node that you are tapping forclick
notifications has child nodes,evt.target
might be one of those child nodes instead of the node you added theclick
handler to.See http://codepen.io/ddopson/pen/erLiv for a demo of this behavior. (click on the inner red box to see that
currentTarget
points at the red div whiletarget
points at outer blue div that the event handler is registered on)Answer to the question asked - getting both `=>` and `this`:
You can do the following...
The spaces are critical as they prevent Coffee from munching
this
into_this
.Using `self` and `->`
Alternatively, do the following ...
This is similar to CQQL's answer, except that I prefer the idiomatic use of
self
as the variable name; my VIM syntax highlighting rules colorself
as a "special" variable just as it would forthis
,arguments
, orprototype
.You may want to access variables set in the constructor from your functions. This would be how you do it (the key is calling the function via
self
while first extractingthis
with a thin arrow):BTW: This is a great explanation of when to use the fat and thin arrow.
Summary: