I try to write a simple snake game on Blazor, but I can't find any way to bind my events on document.
There is an opportunity to bind events on different elements such as div or input.
Like for instance: <input onkeypress="@KeyPressInDiv"/>
Where public void KeyPressInDiv(UIKeyboardEventArgs ev)
{....}
I suppose, that there should be some analogy for a javascript method document.onkeydown = function (evt) {}
I have found several ways for working around this problem:
1) Use JS for binding and invoke blazor code(taken from https://github.com/aesalazar/AsteroidsWasm )
document.onkeydown = function (evt) {
evt = evt || window.event;
DotNet.invokeMethodAsync('Test.ClientSide', 'JsKeyDown', evt.keyCode);
//Prevent all but F5 and F12
if (evt.keyCode !== 116 && evt.keyCode !== 123)
evt.preventDefault();
};
document.onkeyup = function (evt) {
evt = evt || window.event;
DotNet.invokeMethodAsync('Test.ClientSide', 'JsKeyUp', evt.keyCode);
//Prevent all but F5 and F12
if (evt.keyCode !== 116 && evt.keyCode !== 123)
evt.preventDefault();
};
and in c# implement a static class with methods marked by [JSInvokable] and events.
This work, but lead to an awful delay on every press
2) This is possible to add input tag and bind event on it.
This will work really faster than the previous, but:
- it mainly looks like a huck then a solution
- we are not able to catch a number of actions such as Up/DownArrow
Is there a direct way for binding on documents events from blazor?
Update 1: I create simple project for better explanation what I try to achive. https://github.com/XelMed/BlazorSnake
There is 3 implementation of Snake:
1) pure js - this is an expected behavior
2) Using js with blazor - invoked blazor function from JS code with JsInterop
3) Using input tag - binding events on input tag for control Snake