In a fat arrowed function of a coffeescript class, how can I access the scope of the class as well as the function?
Example:
class Example
foo: ->
$('.element').each => # or ->
@bar($(this)) # I want to access 'bar' as well as the jquery element
bar: (element) ->
element.hide()
So in this example, if I use a => then the @ refers to the this of the class but the 'this' is then wrong, whereas if I use a -> for the each, then the 'this' is correctly scoped but but then how do I reference the class function bar?
Thanks!
While mak is right, he fails to point out that in coffee script you rarely need jQuery's each
method, which as you noticed, punches your execution context in the face without your permission.
class Example
foo: ->
for element in $('.element')
@bar $(element)
bar: (element) ->
element.hide()
Coffee script's looping features support the concept of each
without any actual custom library code at all. And they also do not generate a new scope or context meaning you dont need a fat arrow of any kind.
That's because in CoffeeScript @
is an alias for this
i.e. when you compile your .coffee to .js @
will be replaced with this
.
If Example::bar
is ugly, I don't think there are 'prettier' solutions.
You can store a reference to this
before calling .each
:
class Example
foo: ->
self = @
$('.element').each ->
self.bar($(this)) # or self.bar($(@))
bar: (element) ->
element.hide()
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