1

在咖啡脚本中有以下课程:

class Canvas
  constructor: (finder) ->
    @canvas = $(finder)
    @mouse_down()
  mouse_down: ->
    @canvas.mousedown (e) ->
      mouse_x = e.pageX - @offsetLeft
      ### ... ###
      @redraw()
  redraw: ->
    ### ... ###

问题是在函数中调用类对象redraw方法。mousedown最好的解决方案是什么?我只发现:

  mouse_down: ->
    @canvas.mousedown (e) =>
      mouse_x = e.pageX - @canvas[0].offsetLeft
      ### ... ###
      @redraw()
4

2 回答 2

2

看一下这个:

class Canvas
   constructor: (finder) ->
      @canvas = $(finder)
      @mouse_down()
   mouse_down: ->
      redrawCallback = @redraw
      @canvas.mousedown (e) ->
         mouse_x = e.pageX - @offsetLeft
         ### ... ###
         redrawCallback()
   redraw: ->
      ### ... ###

如果 redraw 无论如何都指向@(Canvas 类),那么这样做会更好(无论如何它更安全):

class Canvas
  constructor: (finder) ->
     @canvas = $(finder)
     @mouse_down()
  mouse_down: ->
     redrawCallback = => @redraw()
     @canvas.mousedown (e) ->
        mouse_x = e.pageX - @offsetLeft
        ### ... ###
        redrawCallback()
  redraw: ->
     ### ... ###

PS。尽管这是一个口味问题,但我相信骆驼大小写比下划线更适合方法名称。

于 2012-09-06T13:21:22.063 回答
1

您找到了更好的解决方案。但如果你愿意,你可以这样写:

mouse_down: ->
    self = @ 
    @canvas.mousedown (e) ->
      mouse_x = e.pageX - self.canvas[0].offsetLeft
      ### ... ###
      self.redraw()
于 2012-09-06T10:20:56.933 回答