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)
Arrow functions allow us to use the fat arrow => operator to quickly define JavaScript functions, with or without parameters. We are able to omit the curly braces and the function and return keywords when creating a new JavaScript function to write shorter function syntax.
One of the most heralded features in modern JavaScript is the introduction of arrow functions, sometimes called 'fat arrow' functions, utilizing the new token => . These functions two major benefits - a very clean concise syntax and more intuitive scoping and this binding.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With