Created
February 25, 2021 14:50
-
-
Save adeonhy/2d889c2867f95acb698416c41f9cf901 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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