I'm trying to build a simple app where you can use the arrow keys to do certain things. And trying to get the front end to react appropriately. But so far, I'v not been able to update the data inside x-data.
Simple flow
But this is not working since the event handler can't set this.upPressed from where it is registered.
Any ideas?
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
}
},
}
}
You can assign the object to a variable, and reference that, or, you can wrap the callback such that this will be your object (provided init is called with the correct this).
For the second solution:
init: function() {
document.addEventListener("keydown", e => this.keyDownHandler(e), false);
document.addEventListener("keyup", e => this.keyUpHandler(e), false);
}