I'm wondering is possible somehow to prevent this
keyword to be transformed into _this
inside fat arrow callback (=>
)?
For example:
class someClass
someMethod: ->
$(document).on 'click', '.myclass', (e) =>
# doing things with right context this, it's ok
@anotherMethod()
@oneMoreMethod()
# but here I need jQuery ``this`` pointing to element
$el = $ this # this is transformed into ``_this`` :(
Maybe I missed some option or operator?
UPDATE
I know about the trick like self = this
, but I thought CS has something more elegant..
That's the whole purpose of
=>
.Use
$(e.currentTarget)
to get a handle to the element that would have beenthis
. This is not the same as$(e.target)
which you have already rejected.And no, CoffeeScript can't have anything more elegant way to handle this. You can only have one context for a function. Bound functions aren't unique to CoffeeScript, they're a feature of JavaScript, and the solution is for the calling code to provide another way of accessing the element, which jQuery does with
e.target
ande.currentTarget
.The purpose of the
=>
fat arrow as opposed to the skinny arrow->
is to prevent changing the context ofthis
. You have multiple options here. One option is to store a reference tothis
inside a variable, such as the following.