Coffeescript classes and volume and thick and thin arrows

In a function with bold arrows of the 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 @ refers to this class, but 'this' is wrong, whereas if I use a β†’ for each, then 'this' is correct, but how can I refer to class function bar?

Thanks!

+7
source share
3 answers

This is because CoffeeScript @ has an alias for this , that is, when you compile your .coffee into .js @ , it will be replaced by this .

If Example::bar is ugly, I don't think there are β€œmore beautiful” solutions.

You can save the link to this before calling .each :

 class Example foo: -> self = @ $('.element').each -> self.bar($(this)) # or self.bar($(@)) bar: (element) -> element.hide() 
+10
source

While the poppy is right, it does not indicate that in coffee script you rarely need the jQuery each method, which, as you noticed, deletes your execution context without your permission.

 class Example foo: -> for element in $('.element') @bar $(element) bar: (element) -> element.hide() 

The coffee script looping functions support the concept of each without any actual user library code at all. And they also do not create a new area or context, meaning you do not need a bold arrow of any type.

+16
source

After checking another solution. Here, something appears to me as the most complete sample with each and clicks:

 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)) 
+3
source

All Articles