【问题标题】:Coffeescript - 'this' is always replaced by '_this' in fat arrow callbackCoffeescript - 在胖箭头回调中,'this' 总是被 '_this' 替换
【发布时间】:2014-07-03 04:45:15
【问题描述】:

我想知道是否有可能以某种方式阻止 this 关键字在胖箭头回调 (=>) 中转换为 _this

例如:

class someClass

  someMethod: ->
    $(document).on 'click', '.myclass', (e) =>
      # doing things with right context this, it's ok
      @anotherMethod()
      @oneMoreMethod()

      # but here I need jQuery ``this`` pointing to element
      $el = $ this # this is transformed into ``_this`` :(

也许我错过了一些选项或运算符?

更新 我知道self = this 之类的技巧,但我认为 CS 有更优雅的东西..

【问题讨论】:

  • 尝试使用$(e.target)
  • 一个奇怪的技巧是用<backtick><space>this<backtick>替换this,它使用正常的this。第一个反引号和 this 之间需要空格。看到它here
  • 没有人欠你一个不赞成的评论。有人认为您的问题“不清楚或无用”,或者缺乏研究。可能是因为你的问题没有意义。您在问如何防止 => 明确设计给您的单一、孤独的行为。如果您不希望这种行为,请使用->
  • @vcsjones 当 CoffeeScript 编译器更新时,这种诡计几乎肯定会失败。依赖错误和怪癖是一个非常糟糕的主意,当有合理的解决方案时更是如此。

标签: javascript jquery coffeescript this jquery-callback


【解决方案1】:

这就是=> 的全部目的。

使用$(e.currentTarget) 获取本来是this 的元素的句柄。这与您已经拒绝的$(e.target) 不同。

不,CoffeeScript 不能有任何更优雅的方式来处理这个问题。一个函数只能有一个上下文。绑定函数不是 CoffeeScript 独有的,它们是 JavaScript 的一个特性,解决方案是让调用代码提供另一种访问元素的方式,jQuery 对 e.targete.currentTarget 所做的。

【讨论】:

  • 不确定我是否同意最后一段。我认为旧版本的 CoffeeScript 的行为使得瘦箭头与胖箭头只会影响 @ 的行为方式,而不是文字关键字 this,因为在 @ 中会捕获 this 之前的函数的上下文,而this 将始终作为this 单独存在。
【解决方案2】:

=> 粗箭头相对于细箭头 -> 的目的是防止更改 this 的上下文。您在这里有多种选择。一种选择是将this 的引用存储在变量中,如下所示。

self = @
method: -> @ is self # true

self = @
method: => @ is self # false


class someClass

  someMethod: ->
    self = @
    $(document).on 'click', '.myclass', (e) ->
        # self (by default) refers to your class
        # @ refers to the jquery object (context)

【讨论】:

  • 是的,我知道 JavaScript 技巧.. 我虽然 Coffee 有一些更优雅的东西来处理它..
猜你喜欢
  • 2014-02-28
  • 2012-09-20
  • 2012-06-12
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多