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 ne
CoffeeScript links both this
and @
to the outer context, therefore you cannot access the context that jQuery provided (aka the desired "this"). Use event.target instead:
class PostForm
constructor: ->
$('ul.tabs li').on 'click', (event) =>
tab = $(event.target)
@highlight_tab(tab)
You should probably use evt.currentTarget (which is equivalent to this
) instead of evt.target (which isn't). If the node that you are tapping for click
notifications has child nodes, evt.target
might be one of those child nodes instead of the node you added the click
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 while target
points at outer blue div that the event handler is registered on)
$('ul.tabs li').on 'click', (event) =>
tab = $(event.currentTarget)
@highlight_tab(tab)
You can do the following...
$('ul.tabs li').on 'click', (event) =>
tab = $(` this `) # MAKE SURE TO ADD THE SPACES AROUND `this`
@highlight_tab(tab)
The spaces are critical as they prevent Coffee from munching this
into _this
.
Alternatively, do the following ...
self = this
$('ul.tabs li').on 'click', (event) ->
tab = $(this)
self.highlight_tab(tab)
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 color self
as a "special" variable just as it would for this
, arguments
, or prototype
.
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 extracting this
with a thin arrow):
class PostForm
constructor: ->
self = this
@some_contrived_variable = true
$('ul.tabs li').on 'click', ->
tab = $(this)
self.highlight_tab(tab)
self.set_post_type(tab.attr('data-id'))
highlight_tab: (tab) ->
# Because of the fat arrow here you can now access @ again
if @some_contrived_variable
tab.addClass 'active'
set_post_type: (id) ->
$('#post_type_id').val(id)
BTW: This is a great explanation of when to use the fat and thin arrow.
Summary:
I prefer this version, because I can understand it more easily.
class PostForm
constructor: ->
post_form = this
$('ul.tabs li').on 'click', (event) ->
tab = $(this)
post_form.highlight_tab(tab)