mirror of
https://github.com/fluencelabs/wasm-bindgen
synced 2025-06-22 17:21:35 +00:00
Implement support for js_class
on exported types
Allow defining types which have different names in Rust than they have in JS! (just like can be done with imported types) Closes #1010
This commit is contained in:
28
guide/src/reference/attributes/on-rust-exports/js_class.md
Normal file
28
guide/src/reference/attributes/on-rust-exports/js_class.md
Normal file
@ -0,0 +1,28 @@
|
||||
# `js_class = Blah`
|
||||
|
||||
The `js_class` attribute is used to indicate that all the methods inside an
|
||||
`impl` block should be attached to the specified JS class instead of inferring
|
||||
it from the self type in the `impl` block. The `js_class` attribute is most
|
||||
frequently paired with [the `js_name` attribute](js_name.html) on structs:
|
||||
|
||||
```rust
|
||||
#[wasm_bindgen(js_name = Foo)]
|
||||
pub struct JsFoo { /* ... */ }
|
||||
|
||||
#[wasm_bindgen(js_class = Foo)]
|
||||
impl JsFoo {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new() -> JsFoo { /* ... */ }
|
||||
|
||||
pub fn foo(&self) { /* ... */ }
|
||||
}
|
||||
```
|
||||
|
||||
which is accessed like:
|
||||
|
||||
```rust
|
||||
import { Foo } from './my_module';
|
||||
|
||||
const x = new Foo();
|
||||
x.foo();
|
||||
```
|
@ -22,3 +22,33 @@ import { doTheThing } from './my_module';
|
||||
const x = doTheThing();
|
||||
console.log(x);
|
||||
```
|
||||
|
||||
Like imports, `js_name` can also be used to rename types exported to JS:
|
||||
|
||||
```rust
|
||||
#[wasm_bindgen(js_name = Foo)]
|
||||
pub struct JsFoo {
|
||||
// ..
|
||||
}
|
||||
```
|
||||
|
||||
to be accessed like:
|
||||
|
||||
```js
|
||||
import { Foo } from './my_module';
|
||||
|
||||
// ...
|
||||
```
|
||||
|
||||
Note that attaching methods to the JS class `Foo` should be done via the
|
||||
[`js_class` attribute](js_class.html):
|
||||
|
||||
```rust
|
||||
#[wasm_bindgen(js_name = Foo)]
|
||||
pub struct JsFoo { /* ... */ }
|
||||
|
||||
#[wasm_bindgen(js_class = Foo)]
|
||||
impl JsFoo {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user