Debian Codegraph @

.cargo/vendor/wasm-bindgen/guide/src/reference/static-js-objects.md

raw
1 # Use of `static` to Access JS Objects
2
3 JavaScript modules will often export arbitrary static objects for use with
4 their provided interfaces. These objects can be accessed from Rust by declaring
5 a named `static` in the `extern` block. `wasm-bindgen` will bind a `JsStatic`
6 for these objects, which can be cloned into a `JsValue`. For example, given the
7 following JavaScript:
8
9 ```js
10 let COLORS = {
11 red: 'rgb(255, 0, 0)',
12 green: 'rgb(0, 255, 0)',
13 blue: 'rgb(0, 0, 255)',
14 };
15 ```
16
17 `static` can aid in the access of this object from Rust:
18
19 ```rust
20 #[wasm_bindgen]
21 extern "C" {
22 static COLORS;
23 }
24
25 fn get_colors() -> JsValue {
26 COLORS.clone()
27 }
28 ```
29
30 Since `COLORS` is effectively a JavaScript namespace, we can use the same
31 mechanism to refer directly to namespaces exported from JavaScript modules, and
32 even to exported classes:
33
34 ```js
35 let namespace = {
36 // Members of namespace...
37 };
38
39 class SomeType {
40 // Definition of SomeType...
41 };
42
43 export { SomeType, namespace };
44 ```
45
46 The binding for this module:
47
48 ```rust
49 #[wasm_bindgen(module = "/js/some-rollup.js")]
50 extern "C" {
51 // Likewise with the namespace--this refers to the object directly.
52 #[wasm_bindgen(js_name = namespace)]
53 static NAMESPACE: JsValue;
54
55 // Refer to SomeType's class
56 #[wasm_bindgen(js_name = SomeType)]
57 static SOME_TYPE: JsValue;
58
59 // Other bindings for SomeType
60 type SomeType;
61 #[wasm_bindgen(constructor)]
62 fn new() -> SomeType;
63 }
64 ```