Skip to content

Instantly share code, notes, and snippets.

@adeonhy
Created February 25, 2021 14:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adeonhy/2d889c2867f95acb698416c41f9cf901 to your computer and use it in GitHub Desktop.
Save adeonhy/2d889c2867f95acb698416c41f9cf901 to your computer and use it in GitHub Desktop.
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