【问题标题】:eventlistener once property prevents other eventlistener issueeventlistener once 属性防止其他 eventlistener 问题
【发布时间】:2022-09-27 09:02:46
【问题描述】:
constructor() {
    document.addEventListener(\"keyup\", this.keyStart.bind(this), {once:true});
    document.addEventListener(\"keydown\", this.keySpaceHandler.bind(this));
}
keySpaceHandler(e) {
    if (e.keyCode === 32 && missile_count > 0) {
        ...
    }
}

keyStart(e) {
    if (e.key === \"ArrowLeft\" || e.key === \"ArrowRight\") {
        isGameStart = true;
        if (isGameStart === true) {
            ...
        }
    }
}

我希望 keyStart 只听一次事件,这样它就不会在每次用户使用箭头键时都被调用,而只会在第一次开始游戏时被调用。 当用户按空格键然后按箭头键时会出现问题。因为我将 keyStart 属性设置为 once:true,所以如果在箭头键之前按下任何其他键,它不会监听任何事件。有没有办法解决这个问题,即使用户在箭头键之前按下任何其他键,一旦按下箭头键,就会调用 keyStart 并按预期开始游戏?先感谢您!

  • 因此,您需要将自己的代码编写一次。

标签: javascript


【解决方案1】:

对其进行编码,使其检查事件内部的布尔值,以便您忽略该函数一次又一次地运行。

keyStart(e) {
  if (this.isGameStart) return true;
  if (["ArrowLeft", "ArrowRight"].includes(e.key)) {
    this.isGameStart = true;
  }
}

如果您不想触发事件,您可以通过存储函数引用并调用 removeEventListener 来删除事件

constructor() {
  this.startListenerFunc = this.keyStart.bind(this);
  // this.startListenerFunc = e => this.keyStart(e);
  document.addEventListener("keyup", this.startListenerFunc);
}

keyStart(e) {
  if (["ArrowLeft", "ArrowRight"].includes(e.key)) {
    document.removeEventListener("keyup", this.startListenerFunc);
    this.isGameStart = true;
  }
}

【讨论】:

  • 现在可以了!谢谢!!
【解决方案2】:

时不时地有一些非正式的建议为这个确切的情况添加一个“条件”到once。但我所知道的还没有赢得所需实施者的兴趣。目前,最符合人体工程学的解决方案是使用AbortController,而不是您可以传入addEventListener()signal 选项。

const missile_count = 32;
class Stuff {
  constructor() {
    const controller = new AbortController();
    document.addEventListener("keyup", this.keyStart.bind(this, controller), {
      signal: controller.signal
    });
    document.addEventListener("keydown", this.keySpaceHandler.bind(this));
  }

  keySpaceHandler(e) {
    if (e.keyCode === 32 && missile_count > 0) {
      // ...
    }
  }

  keyStart(controller, e) {
    if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
      controller.abort(); // removes the event handler
      console.log("starting game");
    } else {
      console.log("ignoring other key");
    }
  }
}
const stuff = new Stuff();
Press ArrowLeft or ArrowRight.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2021-01-04
    • 1970-01-01
    相关资源
    最近更新 更多