Hi, i am writting a wasm program, the code below confused me:
use wasm_bindgen::{prelude::Closure, JsCast};
use web_sys;
fn fn() {
let f = Closure::wrap(Box::new(move || {
log::info!("fuck");
}) as Box<dyn Fn()>);
let f_ = f.as_ref().unchecked_ref();
let div = web_sys::window()
.unwrap()
.document()
.unwrap()
.create_element("div")
.unwrap()
.dyn_ref::<web_sys::HtmlElement>()
.unwrap();
div.set_onclick(Some(f_));
f.forget();
}
The set_onclick method of web_sys::HtmlElement accept a parameter with type
Option(&js_sys::Function). From the example of wasm_bindgen book, i know that you can create a closure, and then use
as_ref().unchecked_ref()` to convert the closure you created into a function reference with type js_sys::Function.
The example link is here: web-sys: Closures - The `wasm-bindgen` Guide
Why this can be done? I digged into the source code of Closure and js_sys::Function, but still don't know why.