rust 如何将闭包转换为js_sys::函数?

2admgd59  于 2022-11-12  发布在  其他
关注(0)|答案(2)|浏览(144)

如何将中的本地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()));
r7xajy2e

r7xajy2e1#

我找到了这个。
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!
3ks5zfa0

3ks5zfa02#

答案也可以在wasm_bindgen::closure::Closure页面上找到。

use wasm_bindgen::{closure::Closure, JsCast};

let cb = Closure::new(|| { ... });
let cb = cb.as_ref().unchecked_ref();

相关问题