Debian Codegraph @

.cargo/vendor/wasm-bindgen/guide/src/reference/receiving-js-closures-in-rust.md

raw
1 # Receiving JavaScript Closures in Exported Rust Functions
2
3 You can use the `js-sys` crate to access JavaScript's `Function` type, and
4 invoke that function via `Function.prototype.apply` and
5 `Function.prototype.call`.
6
7 For example, we can wrap a `Vec<u32>` in a new type, export it to JavaScript,
8 and invoke a JavaScript closure on each member of the `Vec`:
9
10 ```rust
11 use wasm_bindgen::prelude::*;
12
13 #[wasm_bindgen]
14 pub struct VecU32 {
15 xs: Vec<u32>,
16 }
17
18 #[wasm_bindgen]
19 impl VecU32 {
20 pub fn each(&self, f: &js_sys::Function) {
21 let this = JsValue::null();
22 for &x in &self.xs {
23 let x = JsValue::from(x);
24 let _ = f.call1(&this, &x);
25 }
26 }
27 }
28 ```
29
30 Since Rust has no function overloading, the `call#` method also requires a
31 number representing the amount of arguments passed to the JavaScript closure.