在 JavaScript 中使用键事件处理程序的 Alpine 正确方法

Alpine correct way of using key event handlers inside of the JavaScript

我正在尝试构建一个简单的应用程序,您可以在其中使用箭头键来执行某些操作。并试图让前端做出适当的反应。但是到目前为止,我还没有能够更新x-data里面的数据。

简单流程

但这不起作用,因为事件处理程序无法从其注册位置设置 this.upPressed。

有什么想法吗?

HTML

<div x-data="loadComponent()" x-init="init">
    Right: <span x-text="rightPressed"></span><br>
    Left: <span x-text="leftPressed"></span><br>
    Up: <span x-text="upPressed"></span><br>
    Down: <span x-text="downPressed"></span>
</div>

JavaScript

function loadComponent() {
    return {
        rightPressed: false,
        leftPressed: false,
        upPressed: false,
        downPressed: false,
    init: function() {
        document.addEventListener("keydown", this.keyDownHandler, false)
            document.addEventListener("keyup", this.keyUpHandler, false)
    },
    keyUpHandler(e) {
      console.log(e.key) //loggin the key up event
      if(e.key == "Right" || e.key == "ArrowRight") {
        this.rightPressed = false
      }
      else if(e.key == "Left" || e.key == "ArrowLeft") {
        this.leftPressed = false
      }
      else if (e.key == "Up" || e.key == "ArrowUp") {
        this.upPressed = false
      }
      else if (e.key == "Down" || e.key == "ArrowDown") {
        this.downPressed = false
      }
        },
    keyDownHandler(e) {
      console.log(e.key) // login the key down event
      if(e.key == "Right" || e.key == "ArrowRight") {
        this.rightPressed = true
      }
      else if(e.key == "Left" || e.key == "ArrowLeft") {
        this.leftPressed = true
      }
      else if (e.key == "Up" || e.key == "ArrowUp") {
        this.upPressed = true
      }
      else if (e.key == "Down" || e.key == "ArrowDown") {
        this.downPressed = true
      }
        },
    }
}

您可以将该对象分配给一个变量,并引用该变量,或者,您可以包装回调,使 this 成为您的对象(前提是 init 使用正确的 this).

对于第二种解决方案:

init: function() {
    document.addEventListener("keydown", e => this.keyDownHandler(e), false);
    document.addEventListener("keyup", e => this.keyUpHandler(e), false);
}