| 1 |
# `js_namespace = blah` |
| 2 |
|
| 3 |
This attribute indicates that the JavaScript type is accessed through the given |
| 4 |
namespace. For example, the `WebAssembly.Module` APIs are all accessed through |
| 5 |
the `WebAssembly` namespace. `js_namespace` can be applied to any import |
| 6 |
(function or type) and whenever the generated JavaScript attempts to reference a |
| 7 |
name (like a class or function name) it'll be accessed through this namespace. |
| 8 |
|
| 9 |
```rust |
| 10 |
#[wasm_bindgen] |
| 11 |
extern "C" { |
| 12 |
#[wasm_bindgen(js_namespace = console)] |
| 13 |
fn log(s: &str); |
| 14 |
|
| 15 |
type Foo; |
| 16 |
#[wasm_bindgen(constructor, js_namespace = Bar)] |
| 17 |
fn new() -> Foo; |
| 18 |
} |
| 19 |
|
| 20 |
log("hello, console!"); |
| 21 |
Foo::new(); |
| 22 |
``` |
| 23 |
|
| 24 |
This is an example of how to bind namespaced items in Rust. The `log` and `Foo::new` functions will |
| 25 |
be available in the Rust module and will be invoked as `console.log` and `new Bar.Foo` in |
| 26 |
JavaScript. |
| 27 |
|
| 28 |
It is also possible to access the JavaScript object under the nested namespace. |
| 29 |
`js_namespace` also accepts the array of the string to specify the namespace. |
| 30 |
|
| 31 |
```rust |
| 32 |
#[wasm_bindgen] |
| 33 |
extern "C" { |
| 34 |
#[wasm_bindgen(js_namespace = ["window", "document"])] |
| 35 |
fn write(s: &str); |
| 36 |
} |
| 37 |
|
| 38 |
write("hello, document!"); |
| 39 |
``` |
| 40 |
|
| 41 |
This example shows how to bind `window.document.write` in Rust. |
| 42 |
|
| 43 |
If all items in the `extern "C" { … }` block have the same `js_namespace = …`: |
| 44 |
|
| 45 |
```rust |
| 46 |
#[wasm_bindgen] |
| 47 |
extern "C" { |
| 48 |
#[wasm_bindgen(js_namespace = Math)] |
| 49 |
fn random() -> f64; |
| 50 |
#[wasm_bindgen(js_namespace = Math)] |
| 51 |
fn log(a: f64) -> f64; |
| 52 |
// ... |
| 53 |
} |
| 54 |
``` |
| 55 |
|
| 56 |
Then that macro argument can also be moved to the outer block: |
| 57 |
|
| 58 |
```rust |
| 59 |
#[wasm_bindgen(js_namespace = Math)] |
| 60 |
extern "C" { |
| 61 |
#[wasm_bindgen] |
| 62 |
fn random() -> f64; |
| 63 |
#[wasm_bindgen] |
| 64 |
fn log(a: f64) -> f64; |
| 65 |
// ... |
| 66 |
} |
| 67 |
``` |
| 68 |
|
| 69 |
`js_namespace = …` on an individual item takes precedence over the outer block's `js_namespace = …`. |