2013-09-04 10 views
9

私はCoffeescriptの使用中にいくつかの範囲の問題を扱っています。var self = this in Coffeescript

drawFirstLine: (currentAngle) -> 
    currentAngle = currentAngle # = 1 

    switch @type 
     # set @endAngle to pick up later on 
     # Math.PI * 2 is the endpoint of a circle divided by seconds times current seconds 
     when "seconds" then @endAngle = Math.PI * 2/60 * @seconds 
     when "minutes" then @endAngle = Math.PI * 2/60 * @minutes 
     when "hours" then @endAngle = Math.PI * 2/24 * @hours 


    @context.arc(@center_x, @center_y, 100, @startAngle, currentAngle, @counterClockWise) 
    @context.lineWidth = 15 

    console.log('drawn') 

    text = "28px sans-serif"; 
    @context.fillText(text, @center_x - 28, @center_y - @canvas.width/5) 

    @context.stroke() 


    currentAngle++; 
    if currentAngle < @endAngle 
     requestAnimationFrame(-> @drawFirstLine(currentAngle/100)) 

あなたは私が何度も何度も、私たちがしている関数を呼び出すしようとしています上記のコードの一番下に見ることができるように。しかし、問題は、別の関数(requestAnimationFrame関数)の中に@drawFirstLineを使用できないことです。プレーンなjavascriptで私はvar self = thisを使用し、自己を参照することができます。しかし、誰かがこれをcoffeescriptで扱う方法を知っていますか?コンパイル事前に

おかげで、

+0

[ネストされた関数の内部で問題を参照するクラスオブジェクト]の複製が可能です。(http://stackoverflow.com/questions/18281886/trouble-referencing-class-object-inside-a-nested-function) – Mathletics

答えて

17

Use the fat arrow.

requestAnimationFrame(=> @drawFirstLine(currentAngle/100)) 

var _this = this; 

requestAnimationFrame(function() { 
    return _this.drawFirstLine(currentAngle/100); 
}); 

それは基本的に何であるかthis関数内thisまたは@を作り、あなたのためのself = thisを行いますその関数が宣言されます。それは非常に便利です、そして、それはおそらく私のお気に入りです。

+0

。あなたの答えをできるだけ早く受け入れます! –

+0

しかし、いくつかのコールバックが深い場合は太った矢印を使用しても問題は発生しませんか?あるいは、それはいつも最も外側のものを指しますか? – RyanWilcox

+3

@RyanWilcox関数をネストするときに '=>'を使い続けると、 'this'が維持されます。 [証拠はこちらです!](http://coffeescript.org/#try:%40foo%20%3D%20'bar'%0A%0Acallback%20%3D%3E%0A%20%20anothercallback%20%3D %3E%0A%20%20%20%20Hollaback%20%3D%3E%0A%20%20%20%20%20%20alert%20%40foo) –

1

私はいつも私の仕事で私のアプリでこれを行います。

drawFirstLine: (currentAngle) -> 
    currentAngle = currentAngle # = 1 
    self = @ 

    .... 

のCoffeeScriptであなたがvarを必要としない、覚えておいてください:これはdrawFirstLine機能のコンテキストにローカルなままになります。 (それはvar self = thisを生成します)。

関連する問題