2014-07-02 32 views
2

我想知道是否有可能以某種方式阻止this關鍵字轉化爲_this裏面的胖箭頭回調(=>)?Coffeescript - '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`` :(

也許我錯過了一些選項,或運營商?

UPDATE 我知道像self = this的伎倆,但我認爲CS有什麼更優雅..

+1

嘗試在我的具體情況下使用'$(e.target)' – elclanrs

+0

「e.target''不是解決方案,我需要使用''this''來獲取具體屬性,我選擇的屬性而不是它的孩子。 – Kosmetika

+1

一個奇怪的伎倆得到這個工作是用'這個'替換'this',它使用正常的'this'按預期。第一個反引號和這個之間需要空格。看到它[這裏](http://coffeescript.org/#try:class%20someClass%0A%0A%20%20someMethod%3A%20-%3E%0A%20%20%20%20%24(document) %。對20'click '%2C%20'.myclass' %2C%圖20(e)%20%3D%3E%0A%20%20%20%20%20%20%23%20doing%20things%20with %20right%20context%20this%2C%20IT的%20ok%0A%20%20%20%20%20%20%40anotherMethod()%0A%20%20%20%20%20%20%40oneMoreMethod()%0A %20%20%20%20%20%20%24%20%3D%20%24%20%60%20this%60) – vcsjones

回答

4

這就是=>的全部目的。

使用$(e.currentTarget)可以獲得this元素的句柄。這與您已經拒絕的$(e.target)不一樣。

並且不,CoffeeScript 不能有什麼更優雅的方式來處理這個。一個函數只能有一個上下文。綁定函數並不是唯一的CoffeeScript,它是JavaScript的一個特性,解決方案是調用代碼提供另一種訪問元素的方式,jQuery使用e.targete.currentTarget

+0

不知道我同意最後一段。我*認爲*舊版本的CoffeeScript表現得如此瘦削與胖箭頭只會影響'@'的表現方式,而不是像'@'這樣的文字關鍵字'this'在函數的上下文之前捕獲'this',並且'this'將總是被單獨留爲'this'。 – vcsjones

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) 
+0

是的,我知道JavaScript的伎倆..我雖然咖啡有一些更優雅的處理它.. – Kosmetika

相關問題