Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript classes and scope and fat and thin arrows

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!

like image 234
Jo P Avatar asked Aug 04 '11 12:08

Jo P


2 Answers

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.

like image 63
Alex Wayne Avatar answered Nov 24 '22 00:11

Alex Wayne


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()
like image 22
mak Avatar answered Nov 24 '22 00:11

mak