SuperSchek
SuperSchek

Reputation: 23

How to remove an eventListener inside a class?

I have tried both of the following versions but I can't get the mousemove eventListener to be removed. I think my limited understanding of scoping inside of classes is causing some confusion, but I'd assume this should work.

export class Line extends Graphic {
  constructor() {
    super()
  }

  handleMouseMoveWhileDrawing(e) {
    console.log(e);
  }

  stopDrawing() {
    document.removeEventListener('mouseup', this.stopDrawing)
    document.removeEventListener('mousemove', this.handleMouseMoveWhileDrawing)
  }

  startDrawing() {
    document.addEventListener('mousemove', this.handleMouseMoveWhileDrawing)
    document.addEventListener('mouseup', this.stopDrawing)
  }
}

new Line().startDrawing()
export class Line extends Graphic {
  constructor() {
    super()
    this.handleMouseMoveWhileDrawing = function(e) {
      console.log(e);
    }
  }

  stopDrawing() {
    document.removeEventListener('mouseup', this.stopDrawing)
    document.removeEventListener('mousemove', this.handleMouseMoveWhileDrawing)
  }

  startDrawing() {
    document.addEventListener('mousemove', this.handleMouseMoveWhileDrawing)
    document.addEventListener('mouseup', this.stopDrawing)
  }
}

new Line().startDrawing()

Any help would be greatly appreciated.

Upvotes: 0

Views: 115

Answers (1)

SuperSchek
SuperSchek

Reputation: 23

@epascarello pushed me in the right direction.

When passing a callback to an eventListener the this parameter is automatically set to the DOM element that the eventListener is attached to. Therefore this.handleMouseMoveWhileDrawing inside the stopDrawing method returned undefined.

I was able to work around this by using .bind() to override the this in the stopDrawing method:

document.addEventListener('mouseup', this.stopDrawing.bind(this))

Upvotes: 1

Related Questions