Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use yew::prelude::*;
use yew::services::console::ConsoleService;
use yew::web_sys::KeyboardEvent;
mod constants;
struct Model {
key: String,
link: ComponentLink<Self>,
}
enum Msg {
KeyPressed(KeyboardEvent),
}
impl Component for Model {
type Message = Msg;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
ConsoleService::log("create");
Self {
link,
key: "".to_string(),
}
}
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::KeyPressed(e) => self.key = KeyboardEvent::key(&e),
}
true
}
fn change(&mut self, _props: Self::Properties) -> ShouldRender {
// Should only return "true" if new properties are different to
// previously received properties.
// This component has no properties so we will always return "false".
false
}
fn view(&self) -> Html {
html! {
<div>
<p>{ format!("{:?}", self.key) }</p>
</div>
}
}
fn rendered(&mut self, first_render: bool) {
if first_render {
let f = self.link.callback(|e| Msg::KeyPressed(e));
let f = Box::new(move |e: KeyboardEvent| f.emit(e)) as Box<dyn FnMut(_)>;
let callback = Closure::wrap(f);
let window = yew::web_sys::window().expect("should get window");
window.set_onkeydown(Some(callback.as_ref().unchecked_ref()));
callback.forget();
}
}
}
#[wasm_bindgen(start)]
pub fn run_app() -> Result<(), JsValue> {
App::<Model>::new().mount_to_body();
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment