I have two files
tools.coffee
tools = {}
tools.pencil = =>
@.started = false
@.mousedown = (e) =>
c.begin()
c.moveTo(e._x, e._y)
@.started = true
@.mousemove = (e) =>
if @.started
c.lineTo(e._x, e._y)
c.stroke()
@.mouseup = (e) =>
if @.started
@.started = false
script.coffee
find_position = (obj) ->
curleft = 0
curtop = 0
curleft = $(obj).offset().left - $(window).scrollLeft()
curtop = $(obj).offset().top - $(window).scrollTop();
{ x: curleft, y: curtop };
init = ->
window.canvas = $('#drawn').get(0)
c = canvas.getContext('2d')
c.lineJoin = "round";
c.lineCap = "round";
c.strokeStyle = "#"+ghex;
c.lineWidth = 1;
tool = tools.pencil
$('#container canvas').bind('mousedown mousemove mouseup', mouse_draw);
mouse_draw = (e) ->
position = find_position(this)
e._x = e.clientX - position.x;
e._y = e.clientY - position.y;
func = tool[e.type];
console.log tools
tools.pencil(e)
$(window).ready =>
init()
The point of the code is to draw on a canvas element if you cannot tell. I have been trying to get this to work for the past couple days off and on and I have not gotten very far. The things I have learned are,
tools.pencil is defined but no methods of pencil are. I cannot figure out why that is.
Thanks for the help I think it just has to do with the scoping built into coffeescript.
The reason is this line:
The “fat arrow” binds the function to the current value of
this. That’ll be the global scope.Using the “thin arrow” (
->) won’t do function binding, so should lead to the expected result.You might however consider something like this instead: