Skip to content

Commit 3031c15

Browse files
committed
Rewrite docs for getters/setters
1 parent c70ed36 commit 3031c15

File tree

1 file changed

+39
-20
lines changed

1 file changed

+39
-20
lines changed
Lines changed: 39 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,27 @@
11
# `getter` and `setter`
22

3-
It is also possible to interact with `Rust` types either by using fields accessors. For example, the following:
3+
The `getter` and `setter` attributes can be used in Rust `impl` blocks to define
4+
properties in JS that act like getters and setters of a field. For example:
45

56
```rust
67
#[wasm_bindgen]
7-
extern "C" {
8-
fn check_modify_and_return_baz_in_js_fields(baz: Baz) -> Baz;
9-
}
10-
11-
#[wasm_bindgen_test]
12-
fn create_and_check_baz_in_rust() {
13-
let baz = check_modify_and_return_baz_in_js_fields(Baz { field: 123 });
14-
assert_eq!(baz.field.unwrap(), 456);
15-
}
16-
17-
#[wasm_bindgen]
18-
#[derive(Default)]
198
pub struct Baz {
209
field: i32,
2110
}
2211

2312
#[wasm_bindgen]
2413
impl Baz {
14+
#[wasm_bindgen(constructor)]
15+
pub fn new(field: i32) -> Baz {
16+
Baz { field }
17+
}
18+
2519
#[wasm_bindgen(getter)]
2620
pub fn field(&self) -> i32 {
2721
self.field
2822
}
2923

30-
#[wasm_bindgen(setter = field)]
24+
#[wasm_bindgen(setter)]
3125
pub fn set_field(&mut self, field: i32) {
3226
self.field = field;
3327
}
@@ -37,9 +31,34 @@ impl Baz {
3731
Can be combined in `JavaScript` like in this snippet:
3832

3933
```js
40-
check_modify_and_return_baz_in_js_fields = (baz) => {
41-
console.log(baz.field, 123);
42-
baz.field = 456;
43-
return baz;
44-
};
45-
```
34+
const obj = new Baz(3);
35+
assert.equal(obj.field, 3);
36+
obj.field = 4;
37+
assert.equal(obj.field, 4);
38+
```
39+
40+
You can also configure the name of the property that is exported in JS like so:
41+
42+
```rust
43+
#[wasm_bindgen]
44+
impl Baz {
45+
#[wasm_bindgen(getter = anotherName)]
46+
pub fn field(&self) -> i32 {
47+
self.field
48+
}
49+
50+
#[wasm_bindgen(setter = anotherName)]
51+
pub fn set_field(&mut self, field: i32) {
52+
self.field = field;
53+
}
54+
}
55+
```
56+
57+
Getters are expected to take no arguments other than `&self` and return the
58+
field's type. Setters are expected to take one argument other than `&mut self`
59+
(or `&self`) and return no values.
60+
61+
The name for a `getter` is by default inferred from the function name it's
62+
attached to. The default name for a `setter` is the function's name minus the
63+
`set_` prefix, and if `set_` isn't a prefix of the function it's an error to not
64+
provide the name explicitly.

0 commit comments

Comments
 (0)