Coffeescript - 'this'在fat arrow回调中总是被'_this'取代 [英] Coffeescript - 'this' is always replaced by '_this' in fat arrow callback
问题描述
我想知道是否可能以某种方式阻止这个
关键字转换成 _this
里面fat arrow回调 =>
)?
例如:
class someClass
someMethod: - >
$(document).on'click','.myclass',(e)=>
#做正确的上下文这个,没关系
@anotherMethod()
@oneMoreMethod()
#但这里我需要jQuery``this``指向到元素
$ el = $ this#这被转换成``_this`` :(
可能我错过了一些选项或操作符?
UPDATE
我知道如 = this
,但我认为CS有更优雅的东西。
=>
。
使用 $(e.currentTarget)
获得一个 元素的句柄,这与
$(e.target)$ c>不一样
e.target
和 e.currentTarget
。 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..
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
.
这篇关于Coffeescript - 'this'在fat arrow回调中总是被'_this'取代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!