-->

Coffeescript - 'this' is always replaced b

2019-07-20 08:49发布

问题:

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)