Skip to content

Commit a7cda70

Browse files
authored
Merge pull request #848 from alexcrichton/closure-docs-again
Tweak more `Closure` docs
2 parents a37fa45 + bb82db9 commit a7cda70

File tree

1 file changed

+41
-3
lines changed

1 file changed

+41
-3
lines changed

src/closure.rs

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
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+
<<<<<<< a37fa45100baddc36695cbf01110bcd9ab638065
7+
=======
8+
//!
9+
//! The `nightly` feature is required for the `Closure` type to be used.
10+
>>>>>>> Tweak more `Closure` docs
611

712
use std::cell::UnsafeCell;
813
#[cfg(feature = "nightly")]
@@ -37,6 +42,8 @@ use throw;
3742
///
3843
/// # Example
3944
///
45+
/// Sample usage of `Closure` to invoke the `setTimeout` API.
46+
///
4047
/// ```rust,no_run
4148
/// #[wasm_bindgen]
4249
/// extern {
@@ -51,11 +58,11 @@ use throw;
5158
///
5259
/// #[wasm_bindgen]
5360
/// pub fn run() -> ClosureHandle {
54-
/// // First up we use `Closure::new` to wrap up a Rust closure and create
61+
/// // First up we use `Closure::wrap` to wrap up a Rust closure and create
5562
/// a JS closure.
56-
/// let cb = Closure::new(|| {
63+
/// let cb = Closure::wrap(Box::new(move || {
5764
/// log("timeout elapsed!");
58-
/// });
65+
/// }) as Box<FnMut()>);
5966
///
6067
/// // Next we pass this via reference to the `setTimeout` function, and
6168
/// // `setTimeout` gets a handle to the corresponding JS closure.
@@ -67,6 +74,37 @@ use throw;
6774
/// ClosureHandle(cb)
6875
/// }
6976
/// ```
77+
///
78+
/// Sample usage of the same example as above except using `web_sys` instead
79+
///
80+
/// ```rust,no_run
81+
/// extern crate wasm_bindgen;
82+
/// extern crate web_sys;
83+
///
84+
/// use wasm_bindgen::JsCast;
85+
///
86+
/// #[wasm_bindgen]
87+
/// pub struct ClosureHandle(Closure<FnMut()>);
88+
///
89+
/// #[wasm_bindgen]
90+
/// pub fn run() -> ClosureHandle {
91+
/// let cb = Closure::wrap(Box::new(move || {
92+
/// web_sys::console::log_1(&"timeout elapsed!".into());
93+
/// }) as Box<FnMut()>);
94+
///
95+
/// let window = web_sys::window().unwrap();
96+
/// window.set_timeout_with_callback_and_timeout_and_arguments_0(
97+
/// // Note this method call, which uses `as_ref()` to get a `JsValue`
98+
/// // from our `Closure` which is then converted to a `&Function`
99+
/// // using the `JsCast::unchecked_ref` function.
100+
/// cb.as_ref().unchecked_ref(),
101+
/// 1_000,
102+
/// );
103+
///
104+
/// // same as above
105+
/// ClosureHandle(cb)
106+
/// }
107+
/// ```
70108
pub struct Closure<T: ?Sized> {
71109
js: ManuallyDrop<JsValue>,
72110
_keep_this_data_alive: Rc<UnsafeCell<Box<T>>>,

0 commit comments

Comments
 (0)