Search code examples
javascriptcoffeescriptdom-eventsdry

How can I run a coffeescript method that depends on the js event while maintaining DRY code?


I want to DRY up this code:

@$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()

I want to having something to the effect of:

@$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...

The thing is, how do I alternate between @player?.mouseUp(), @player?.mouseDown() and @player?.mouseMove() while maintaining DRY code?


Solution

  • To expand on pdoherty926's answer, you want to somehow do the same thing, but invoke different methods on @player. If you control the method names and you can always use the event type, you can do what pdoherty926 suggests -- otherwise, here's a suggestion for a more explicit solution:

    @$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]()