How to convert a local closure into a js_sys::Function?
I want to do something like this:
let canvas = document.get_element_by_id("canvas").unwrap();
let e: web_sys::HtmlElement = canvas.dyn_into().unwrap();
let f = || {};
e.set_onresize(Some(&f.into()));
I have found a solution here:
let f = Closure::wrap(Box::new(move || { /* whatever */}) as Box<dyn FnMut()>);
e.set_onresize(Some(f.as_ref().unchecked_ref()));
f.forget(); // It is not good practice, just for simplification!
An answer can be found on the wasm_bindgen::closure::Closure page, as well.
use wasm_bindgen::{closure::Closure, JsCast};
let cb = Closure::new(|| { ... });
let cb = cb.as_ref().unchecked_ref();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With