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!
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()
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.
After checking different solution. Here something appear for me as the most complete sample with each and click :
class MainApp
self = []
constructor: ->
self = @
toDoOnClick: (event) ->
self.bar($(event.target)) #hide the clicked object
bar: (element) ->
element.hide()
sampleMethod:->
$(".myDiv").click (e) -> self.toDoOnClick(e)
$('.element').each ->
self.bar($(this))
来源:https://stackoverflow.com/questions/6941442/coffeescript-classes-and-scope-and-fat-and-thin-arrows