Coffeescript - '这个'总是被' _this'取代。在胖箭头回调

时间:2014-07-02 20:29:16

标签: javascript jquery coffeescript this jquery-callback

我想知道有可能以某种方式阻止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有更优雅的东西......

2 个答案:

答案 0 :(得分:4)

=>胖箭头而不是瘦箭头->的目的是防止更改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)

答案 1 :(得分:4)

这是=>的全部目的。

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

不,CoffeeScript 无法有更优雅的方式来处理这个问题。一个函数只能有一个上下文。绑定函数对于CoffeeScript来说并不是唯一的,它们是JavaScript的一个特性,解决方案是让调用代码提供另一种访问元素的方式,jQuery使用e.target和{{{ 1}}。

相关问题