Coffeescript classes and scope and fat and thin arrows

China☆狼群 提交于 2019-12-05 05:34:48

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