Coffeescript - 'this' is always replaced by '_this' in fat arrow callback

爷,独闯天下 提交于 2019-12-24 02:45:22

问题


I'm wondering is possible somehow to prevent this keyword to be transformed into _this inside fat arrow callback (=>)?

For example:

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`` :(

Maybe I missed some option or operator?

UPDATE I know about the trick like self = this, but I thought CS has something more elegant..


回答1:


That's the whole purpose of =>.

Use $(e.currentTarget) to get a handle to the element that would have been this. This is not the same as $(e.target) which you have already rejected.

And no, CoffeeScript can't have anything more elegant way to handle this. You can only have one context for a function. Bound functions aren't unique to CoffeeScript, they're a feature of JavaScript, and the solution is for the calling code to provide another way of accessing the element, which jQuery does with e.target and e.currentTarget.




回答2:


The purpose of the => fat arrow as opposed to the skinny arrow -> is to prevent changing the context of this. You have multiple options here. One option is to store a reference to this inside a variable, such as the following.

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)


来源:https://stackoverflow.com/questions/24540478/coffeescript-this-is-always-replaced-by-this-in-fat-arrow-callback

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