3
3
//! This module defines the `Closure` type which is used to pass "owned
4
4
//! closures" from Rust to JS. Some more details can be found on the `Closure`
5
5
//! type itself.
6
- //!
6
+ //!
7
7
//! The `nightly` feature is required for the `Closure` type to be used.
8
8
9
9
use std:: cell:: UnsafeCell ;
@@ -39,6 +39,8 @@ use throw;
39
39
///
40
40
/// # Example
41
41
///
42
+ /// Sample usage of `Closure` to invoke the `setTimeout` API.
43
+ ///
42
44
/// ```rust,no_run
43
45
/// #[wasm_bindgen]
44
46
/// extern {
@@ -55,9 +57,9 @@ use throw;
55
57
/// pub fn run() -> ClosureHandle {
56
58
/// // First up we use `Closure::new` to wrap up a Rust closure and create
57
59
/// a JS closure.
58
- /// let cb = Closure::new(|| {
60
+ /// let cb = Closure::wrap(Box:: new(move || {
59
61
/// log("timeout elapsed!");
60
- /// });
62
+ /// }) as Box<FnMut()>) ;
61
63
///
62
64
/// // Next we pass this via reference to the `setTimeout` function, and
63
65
/// // `setTimeout` gets a handle to the corresponding JS closure.
@@ -69,6 +71,37 @@ use throw;
69
71
/// ClosureHandle(cb)
70
72
/// }
71
73
/// ```
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
+ /// ```
72
105
pub struct Closure < T : ?Sized > {
73
106
js : ManuallyDrop < JsValue > ,
74
107
_keep_this_data_alive : Rc < UnsafeCell < Box < T > > > ,
0 commit comments