| 1 |
# `getter` and `setter` |
| 2 |
|
| 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: |
| 5 |
|
| 6 |
```rust |
| 7 |
#[wasm_bindgen] |
| 8 |
pub struct Baz { |
| 9 |
field: i32, |
| 10 |
} |
| 11 |
|
| 12 |
#[wasm_bindgen] |
| 13 |
impl Baz { |
| 14 |
#[wasm_bindgen(constructor)] |
| 15 |
pub fn new(field: i32) -> Baz { |
| 16 |
Baz { field } |
| 17 |
} |
| 18 |
|
| 19 |
#[wasm_bindgen(getter)] |
| 20 |
pub fn field(&self) -> i32 { |
| 21 |
self.field |
| 22 |
} |
| 23 |
|
| 24 |
#[wasm_bindgen(setter)] |
| 25 |
pub fn set_field(&mut self, field: i32) { |
| 26 |
self.field = field; |
| 27 |
} |
| 28 |
} |
| 29 |
``` |
| 30 |
|
| 31 |
Can be combined in `JavaScript` like in this snippet: |
| 32 |
|
| 33 |
```js |
| 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. |