如何将闭包转换为js_sys :: Function?

时间:2020-02-04 10:04:24

标签: rust webassembly wasm-bindgen

如何将本地closure转换为js_sys::Funtion

我想做这样的事情:

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()));

1 个答案:

答案 0 :(得分:1)

我发现了这个。

https://rustwasm.github.io/wasm-bindgen/reference/passing-rust-closures-to-js.html

就像:

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!