从箭头函数(OOP)中删除ES6 removeEventListener

时间:2017-09-02 12:56:06

标签: javascript oop ecmascript-6 arrow-functions

我有一个这样的课程:

    class Hanoi{

      constructor(canvas) {
        //construcor things
      }

      onMouseDown(e) {
    for (var i = 0; i < this.pieces.length; i++) {
      let piece = this.pieces[i];
      if (piece.isClicked(e)) {
        this.isDragging = true;
        this.dragPiece = piece;
        this.bound = evt => this.onMouseMove(evt);
        this.canvas.addEventListener("mousemove", ev =>{this.onMouseMove(ev)});
        this.canvas.addEventListener("mouseup", ev =>{this.onMouseUp(ev)});
        this.draw();
      }

      onMouseMove(e) {

    this.dragPiece.x = e.clientX;
    this.dragPiece.y = e.clientY;
    this.draw();
  }

  onMouseUp(e) {
    this.canvas.removeEventListener("mousemove", this.onMouseMove);
    this.canvas.removeEventListener("mouseup", this.onMouseUp);
    this.isDragging = false;
    this.draw();
  }

onMouseDown添加两个事件侦听器,但由于箭头函数,我无法在调用onMouseUp时删除它们。

处理此问题的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

尝试以下方法:

...

constructor(canvas) {
  this.onMouseMove = this.onMouseMove.bind(this);
  this.onMouseUp = this.onMouseUp.bind(this);
}

onMouseDown(e) {
  ...
  this.canvas.addEventListener("mousemove", this.onMouseMove);
  this.canvas.addEventListener("mouseup", this.onMouseUp});
  ...
}

onMouseUp(e) {
  this.canvas.removeEventListener("mousemove", this.onMouseMove);
  this.canvas.removeEventListener("mouseup", this.onMouseUp);
  ...
}

答案 1 :(得分:0)

如果您想稍后引用该函数,最好使用命名的普通函数定义,例如,删除。但是,如果您坚持使用箭头,您仍然可以按照以下步骤操作;

您可以将箭头函数表达式赋值给变量,同时将其作为回调传递。然后使用该名称删除。因此,如果您不想丢弃全局命名空间,则可以始终使用周围的函数对象来存储箭头函数。在这种特殊情况下,我将"click"事件侦听器回调命名为X并将"muouseup"箭头函数存储在该函数对象的muel属性下,该属性在触发时自行删除。

像;

btt.addEventListener("click", function X(e){
  e.target.textContent === "Add Listener" ? (e.target.addEventListener("mouseup", X.muel = e => {
                                                                          e.target.removeEventListener("mouseup", X.muel);
                                                                          console.log("mouse up fired and event listener removed");
                                                                        }),
                                             e.target.textContent = "Remove Listener")
                                          : e.target.textContent = "Add Listener";
                              });
<button id="btt">Add Listener</button>