Coffeescript classes and scope and fat and thin arrows

半世苍凉 提交于 2019-12-07 01:12:02

问题


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!


回答1:


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()



回答2:


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.




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!