Created
October 30, 2018 01:11
-
-
Save rippinrobr/836ec1260db20f5c8bd23ec9c1224d5f to your computer and use it in GitHub Desktop.
The two functions used to create a click event handler for the Rust Click button
This file contains 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
// click_examples_init is called from the init() function in src/lib.rs | |
// it is responsible for registering a click event handler. If there is no | |
// element found with the given id, then an alert button is displayed with | |
// an error message | |
pub fn click_examples_init(elem_id: String, txt_id: String) { | |
match super::get_element_by_id(&elem_id) { | |
Some(btn) => register_click_handler(btn.as_ref() as &web_sys::EventTarget, txt_id), | |
None => super::alert(&format!("No element was found with the id {}", elem_id)), | |
}; | |
} | |
// register_click_handler first creates the closure that will handle the event | |
// then it adds the listener to the button | |
fn register_click_handler(btn: &web_sys::EventTarget, txt_id: String) { | |
let btn_closure = Closure::wrap(Box::new(move |evt: web_sys::MouseEvent| { | |
set_inner_text(&txt_id, evt, "[rust handler]"); | |
}) as Box<FnMut(_)>); | |
btn.add_event_listener_with_callback("click", btn_closure.as_ref().unchecked_ref()) | |
.unwrap(); | |
btn_closure.forget(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment