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
+ <<<<<<< a37fa45100baddc36695cbf01110bcd9ab638065
7
+ =======
8
+ //!
9
+ //! The `nightly` feature is required for the `Closure ` type to be used.
10
+ >>>>>>> Tweak more `Closure ` docs
6
11
7
12
use std:: cell:: UnsafeCell ;
8
13
#[ cfg( feature = "nightly") ]
@@ -37,6 +42,8 @@ use throw;
37
42
///
38
43
/// # Example
39
44
///
45
+ /// Sample usage of `Closure` to invoke the `setTimeout` API.
46
+ ///
40
47
/// ```rust,no_run
41
48
/// #[wasm_bindgen]
42
49
/// extern {
@@ -51,11 +58,11 @@ use throw;
51
58
///
52
59
/// #[wasm_bindgen]
53
60
/// 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
55
62
/// a JS closure.
56
- /// let cb = Closure::new(|| {
63
+ /// let cb = Closure::wrap(Box:: new(move || {
57
64
/// log("timeout elapsed!");
58
- /// });
65
+ /// }) as Box<FnMut()>) ;
59
66
///
60
67
/// // Next we pass this via reference to the `setTimeout` function, and
61
68
/// // `setTimeout` gets a handle to the corresponding JS closure.
@@ -67,6 +74,37 @@ use throw;
67
74
/// ClosureHandle(cb)
68
75
/// }
69
76
/// ```
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
+ /// ```
70
108
pub struct Closure < T : ?Sized > {
71
109
js: ManuallyDrop <JsValue >,
72
110
_keep_this_data_alive: Rc <UnsafeCell <Box <T >>>,
0 commit comments