咖啡脚本 - 'this'总是在胖箭头回调中被'_this'替换



我想知道是否有可能以某种方式阻止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.currentTarget)来获取本应是this的元素的句柄。这与您已经拒绝的$(e.target)不一样。

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

与窄箭头->相反,=>胖箭头的目的是防止更改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)

最新更新