Skip to content

Commit cc9eb0a

Browse files
committed
Tweak more Closure docs
Show off usage of the stable `Closure::wrap` instead of `Closure::new` and additionally add an explicit example of using it with `web_sys`. Closes #843
1 parent 1ee5790 commit cc9eb0a

File tree

1 file changed

+36
-3
lines changed

1 file changed

+36
-3
lines changed

src/closure.rs

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
//! This module defines the `Closure` type which is used to pass "owned
44
//! closures" from Rust to JS. Some more details can be found on the `Closure`
55
//! type itself.
6-
//!
6+
//!
77
//! The `nightly` feature is required for the `Closure` type to be used.
88
99
use std::cell::UnsafeCell;
@@ -39,6 +39,8 @@ use throw;
3939
///
4040
/// # Example
4141
///
42+
/// Sample usage of `Closure` to invoke the `setTimeout` API.
43+
///
4244
/// ```rust,no_run
4345
/// #[wasm_bindgen]
4446
/// extern {
@@ -55,9 +57,9 @@ use throw;
5557
/// pub fn run() -> ClosureHandle {
5658
/// // First up we use `Closure::new` to wrap up a Rust closure and create
5759
/// a JS closure.
58-
/// let cb = Closure::new(|| {
60+
/// let cb = Closure::wrap(Box::new(move || {
5961
/// log("timeout elapsed!");
60-
/// });
62+
/// }) as Box<FnMut()>);
6163
///
6264
/// // Next we pass this via reference to the `setTimeout` function, and
6365
/// // `setTimeout` gets a handle to the corresponding JS closure.
@@ -69,6 +71,37 @@ use throw;
6971
/// ClosureHandle(cb)
7072
/// }
7173
/// ```
74+
///
75+
/// Sample usage of the same example as above except using `web_sys` instead
76+
///
77+
/// ```rust,no_run
78+
/// extern crate wasm_bindgen;
79+
/// extern crate web_sys;
80+
///
81+
/// use wasm_bindgen::JsCast;
82+
///
83+
/// #[wasm_bindgen]
84+
/// pub struct ClosureHandle(Closure<FnMut()>);
85+
///
86+
/// #[wasm_bindgen]
87+
/// pub fn run() -> ClosureHandle {
88+
/// let cb = Closure::wrap(Box::new(move || {
89+
/// web_sys::console::log_1(&"timeout elapsed!".into());
90+
/// }) as Box<FnMut()>);
91+
///
92+
/// let window = web_sys::window().unwrap();
93+
/// window.set_timeout_with_callback_and_timeout_and_arguments_0(
94+
/// // Note this method call, which uses `as_ref()` to get a `JsValue`
95+
/// // from our `Closure` which is then converted to a `&Function`
96+
/// // using the `JsCast::unchecked_ref` function.
97+
/// cb.as_ref().unchecked_ref(),
98+
/// 1_000,
99+
/// );
100+
///
101+
/// // same as above
102+
/// ClosureHandle(cb)
103+
/// }
104+
/// ```
72105
pub struct Closure<T: ?Sized> {
73106
js: ManuallyDrop<JsValue>,
74107
_keep_this_data_alive: Rc<UnsafeCell<Box<T>>>,

0 commit comments

Comments
 (0)