How to use the KeyboardService in Yew


I try to learn the web framework Yew by making a game with it. The book is very helpful but it don't speak so much about services. Currently, I want to handle keyboard input, that's my code in the create function inside the main component :

let key = web_sys::Text::new_with_data("space").unwrap();

let input_handler = KeyboardService::register_key_down(&key, link.callback(|key_event: KeyboardEvent| Msg::KeyDown(key_event)));

I save the input_handler in my Model :

Self {
    /* link and other fields */

But when I compile and I press the space key, nothing happen. I also try to write "space" instead of "Space", but nothing change.

Please, help me :sob:

After some investigation, I figure out that my problem come from the Event Target. I need to use yew::utils::window() for the Event Target instead of my Text which do nothing.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.