I am dealing with some scope issues while using 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) )
As you can see at the bottom of the above code I am trying to call the function where we are in, again and again. But the problem is that I can't use @drawFirstLine
inside another function(the requestAnimationFrame function). In plain javascript I can use var self = this
and refer to self. But does anyone know how to deal with this in coffeescript?
Thanks in advance,
As others have explained, var self = this; allows code in a closure to refer back to the parent scope.
The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.
With the rise of ES6/7 and TypeScript, it seemed like CoffeeScript would become obsolete. But it's not. CoffeeScript was one of the pioneers of the compile-to-JavaScript concept. In fact, some of things you now see in the modern JavaScript appeared in the first version of CoffeeScript some 8 years ago.
To define a function here, we have to use a thin arrow (->). Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below. (function() {}); It is not mandatory to use the return keyword in CoffeeScript.
Use the fat arrow.
requestAnimationFrame( => @drawFirstLine(currentAngle / 100) )
which compiles to:
var _this = this;
requestAnimationFrame(function() {
return _this.drawFirstLine(currentAngle / 100);
});
It basically does the self = this
for you, making this
or @
inside the function what this
is when that function is declared. It's very handy, and it's probably my favorite feature of coffeescript.
I do this all the time in my app at work.
drawFirstLine: (currentAngle) ->
currentAngle = currentAngle # = 1
self = @
....
Remember, in Coffeescript you don't need var
: this will stay local to the context of the drawFirstLine
function. (it'll generate var self = this
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With