如何在保持DRY代码的同时运行依赖于js事件的coffeescript方法?

时间:2013-09-03 18:53:02

标签: javascript javascript-events coffeescript dry

我想干掉这段代码:

@$canvas.on 'mousemove', (e) =>
  return unless @running
  @mouseTarget.set @board.x + e.clientX, @board.y + e.clientY * 2
  @player?.mouseMove()

@$canvas.on 'mousedown', (e) =>
  return unless @running
  @mouseTarget.set @board.x + e.clientX, @board.y + e.clientY * 2
  @player?.mouseDown()

@$canvas.on 'mouseup', (e) =>
  return unless @running
  @mouseTarget.set @board.x + e.clientX, @board.y + e.clientY * 2
  @player?.mouseUp()

我希望有一些效果:

@$canvas.on 'mousemove', 'mousedown', 'mouseup' -> @mouseAction

mouseAction: (e) =>
  return unless @running
  @mouseTarget.set @board.x + e.clientX, @board.y + e.clientY * 2
  @player?.mouseUp() # here is the problem...

问题是,在维护DRY代码的同时,如何在@player?.mouseUp(),@ player?.mouseDown()和@player?.mouseMove()之间切换?

2 个答案:

答案 0 :(得分:1)

要扩展pdoherty926的答案,你想以某种方式做同样的事情,但在@player上调用不同的方法。如果您控制方法名称并且您始终可以使用事件类型,则可以执行pdoherty926建议的操作 - 否则,这里有一个更明确的解决方案的建议:

@$canvas.on 'mousemove', @mouseAction 'mouseMove'
@$canvas.on 'mousedown', @mouseAction 'mouseDown'
@$canvas.on 'mouseup', @mouseAction 'mouseUp'

mouseAction: (action) =>
  (e) =>
   return unless @running
   @mouseTarget.set @board.x + e.clientX, @board.y + e.clientY * 2
   @player?[action]()

答案 1 :(得分:0)

你可以尝试:

capitaliseFirstLetter = (string) -> string.charAt(0).toUpperCase() + string.slice(1)
# you could also include the underscore.string library and use _.capitalize

event_type = "mouse#{capitaliseFirstLetter(e.type.split('mouse')[1])}"
@player[event_type]()