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:
Alex Crichton
2018-11-05 12:29:14 -08:00
parent 3c31a32d51
commit 16d5243362
8 changed files with 142 additions and 31 deletions

View 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();
```

View File

@ -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 {
// ...
}
```