| 1 |
# `js_name = blah` |
| 2 |
|
| 3 |
The `js_name` attribute can be used to bind to a different function in |
| 4 |
JavaScript than the identifier that's defined in Rust. |
| 5 |
|
| 6 |
Most often, this is used to convert a camel-cased JavaScript identifier into a |
| 7 |
snake-cased Rust identifier: |
| 8 |
|
| 9 |
```rust |
| 10 |
#[wasm_bindgen] |
| 11 |
extern "C" { |
| 12 |
#[wasm_bindgen(js_name = jsOftenUsesCamelCase)] |
| 13 |
fn js_often_uses_camel_case() -> u32; |
| 14 |
} |
| 15 |
``` |
| 16 |
|
| 17 |
Sometimes, it is used to bind to JavaScript identifiers that are not valid Rust |
| 18 |
identifiers, in which case `js_name = "some string"` is used instead of `js_name |
| 19 |
= ident`: |
| 20 |
|
| 21 |
```rust |
| 22 |
#[wasm_bindgen] |
| 23 |
extern "C" { |
| 24 |
#[wasm_bindgen(js_name = "$$$")] |
| 25 |
fn cash_money() -> u32; |
| 26 |
} |
| 27 |
``` |
| 28 |
However, you can also use `js_name` to define multiple signatures for |
| 29 |
polymorphic JavaScript functions: |
| 30 |
|
| 31 |
```rust |
| 32 |
#[wasm_bindgen] |
| 33 |
extern "C" { |
| 34 |
#[wasm_bindgen(js_namespace = console, js_name = log)] |
| 35 |
fn console_log_str(s: &str); |
| 36 |
|
| 37 |
#[wasm_bindgen(js_namespace = console, js_name = log)] |
| 38 |
fn console_log_u32(n: u32); |
| 39 |
|
| 40 |
#[wasm_bindgen(js_namespace = console, js_name = log)] |
| 41 |
fn console_log_many(a: u32, b: &JsValue); |
| 42 |
} |
| 43 |
``` |
| 44 |
|
| 45 |
All of these functions will call `console.log` in JavaScript, but each |
| 46 |
identifier will have only one signature in Rust. |
| 47 |
|
| 48 |
Note that if you use `js_name` when importing a type you'll also need to use the |
| 49 |
[`js_class` attribute][jsclass] when defining methods on the type: |
| 50 |
|
| 51 |
```rust |
| 52 |
#[wasm_bindgen] |
| 53 |
extern "C" { |
| 54 |
#[wasm_bindgen(js_name = String)] |
| 55 |
type JsString; |
| 56 |
#[wasm_bindgen(method, getter, js_class = "String")] |
| 57 |
pub fn length(this: &JsString) -> u32; |
| 58 |
} |
| 59 |
``` |
| 60 |
|
| 61 |
The `js_name` attribute can also be used in situations where a JavaScript module uses |
| 62 |
`export default`. In this case, setting the `js_name` attribute to "default" on the |
| 63 |
`type` declaration, and the [`js_class` attribute][jsclass] to "default" on any methods |
| 64 |
on the exported object will generate the correct imports. |
| 65 |
|
| 66 |
|
| 67 |
For example, a module that would be imported directly in JavaScript: |
| 68 |
|
| 69 |
```javascript |
| 70 |
import Foo from "bar"; |
| 71 |
|
| 72 |
let f = new Foo(); |
| 73 |
``` |
| 74 |
|
| 75 |
Could be accessed using this definition in Rust: |
| 76 |
|
| 77 |
```rust |
| 78 |
#[wasm_bindgen(module = "bar")] |
| 79 |
extern "C" { |
| 80 |
#[wasm_bindgen(js_name = default)] |
| 81 |
type Foo; |
| 82 |
#[wasm_bindgen(constructor, js_class = default)] |
| 83 |
pub fn new() -> Foo; |
| 84 |
} |
| 85 |
``` |
| 86 |
|
| 87 |
[jsclass]: js_class.html |