| 1 |
# Passing Rust Closures to Imported JavaScript Functions |
| 2 |
|
| 3 |
The `#[wasm_bindgen]` attribute supports Rust closures being passed to |
| 4 |
JavaScript in two variants: |
| 5 |
|
| 6 |
1. Stack-lifetime closures that should not be invoked by JavaScript again after |
| 7 |
the imported JavaScript function that the closure was passed to returns. |
| 8 |
|
| 9 |
2. Heap-allocated closures that can be invoked any number of times, but must be |
| 10 |
explicitly deallocated when finished. |
| 11 |
|
| 12 |
## Stack-Lifetime Closures |
| 13 |
|
| 14 |
Closures with a stack lifetime are passed to JavaScript as either `&dyn Fn` or `&mut |
| 15 |
dyn FnMut` trait objects: |
| 16 |
|
| 17 |
```rust |
| 18 |
// Import JS functions that take closures |
| 19 |
|
| 20 |
#[wasm_bindgen] |
| 21 |
extern "C" { |
| 22 |
fn takes_immutable_closure(f: &dyn Fn()); |
| 23 |
|
| 24 |
fn takes_mutable_closure(f: &mut dyn FnMut()); |
| 25 |
} |
| 26 |
|
| 27 |
// Usage |
| 28 |
|
| 29 |
takes_immutable_closure(&|| { |
| 30 |
// ... |
| 31 |
}); |
| 32 |
|
| 33 |
let mut times_called = 0; |
| 34 |
takes_mutable_closure(&mut || { |
| 35 |
times_called += 1; |
| 36 |
}); |
| 37 |
``` |
| 38 |
|
| 39 |
**Once these imported functions return, the closures that were given to them |
| 40 |
will become invalidated, and any future attempts to call those closures from |
| 41 |
JavaScript will raise an exception.** |
| 42 |
|
| 43 |
Closures also support arguments and return values like exports do, for example: |
| 44 |
|
| 45 |
```rust |
| 46 |
#[wasm_bindgen] |
| 47 |
extern "C" { |
| 48 |
fn takes_closure_that_takes_int_and_returns_string(x: &dyn Fn(u32) -> String); |
| 49 |
} |
| 50 |
|
| 51 |
takes_closure_that_takes_int_and_returns_string(&|x: u32| -> String { |
| 52 |
format!("x is {}", x) |
| 53 |
}); |
| 54 |
``` |
| 55 |
|
| 56 |
## Heap-Allocated Closures |
| 57 |
|
| 58 |
Sometimes the discipline of stack-lifetime closures is not desired. For example, |
| 59 |
you'd like to schedule a closure to be run on the next turn of the event loop in |
| 60 |
JavaScript through `setTimeout`. For this, you want the imported function to |
| 61 |
return but the JavaScript closure still needs to be valid! |
| 62 |
|
| 63 |
For this scenario, you need the `Closure` type, which is defined in the |
| 64 |
`wasm_bindgen` crate, exported in `wasm_bindgen::prelude`, and represents a |
| 65 |
"long lived" closure. |
| 66 |
|
| 67 |
The validity of the JavaScript closure is tied to the lifetime of the `Closure` |
| 68 |
in Rust. **Once a `Closure` is dropped, it will deallocate its internal memory |
| 69 |
and invalidate the corresponding JavaScript function so that any further |
| 70 |
attempts to invoke it raise an exception.** |
| 71 |
|
| 72 |
Like stack closures a `Closure` supports both `Fn` and `FnMut` closures, as well |
| 73 |
as arguments and returns. |
| 74 |
|
| 75 |
```rust |
| 76 |
#[wasm_bindgen] |
| 77 |
extern "C" { |
| 78 |
fn setInterval(closure: &Closure<dyn FnMut()>, millis: u32) -> f64; |
| 79 |
fn clearInterval(token: f64); |
| 80 |
|
| 81 |
#[wasm_bindgen(js_namespace = console)] |
| 82 |
fn log(s: &str); |
| 83 |
} |
| 84 |
|
| 85 |
#[wasm_bindgen] |
| 86 |
pub struct Interval { |
| 87 |
closure: Closure<dyn FnMut()>, |
| 88 |
token: f64, |
| 89 |
} |
| 90 |
|
| 91 |
impl Interval { |
| 92 |
pub fn new<F: 'static>(millis: u32, f: F) -> Interval |
| 93 |
where |
| 94 |
F: FnMut() |
| 95 |
{ |
| 96 |
// Construct a new closure. |
| 97 |
let closure = Closure::new(f); |
| 98 |
|
| 99 |
// Pass the closure to JS, to run every n milliseconds. |
| 100 |
let token = setInterval(&closure, millis); |
| 101 |
|
| 102 |
Interval { closure, token } |
| 103 |
} |
| 104 |
} |
| 105 |
|
| 106 |
// When the Interval is destroyed, clear its `setInterval` timer. |
| 107 |
impl Drop for Interval { |
| 108 |
fn drop(&mut self) { |
| 109 |
clearInterval(self.token); |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
// Keep logging "hello" every second until the resulting `Interval` is dropped. |
| 114 |
#[wasm_bindgen] |
| 115 |
pub fn hello() -> Interval { |
| 116 |
Interval::new(1_000, || log("hello")) |
| 117 |
} |
| 118 |
``` |