Debian Codegraph @

.cargo/vendor/wasm-bindgen/guide/src/reference/attributes/on-js-imports/indexing-getter-setter-deleter.md

raw
1 # `indexing_getter`, `indexing_setter`, and `indexing_deleter`
2
3 These three attributes indicate that a method is an dynamically intercepted
4 getter, setter, or deleter on the receiver object itself, rather than a direct
5 access of the receiver's properties. It is equivalent calling the Proxy handler
6 for the `obj[prop]` operation with some dynamic `prop` variable in JavaScript,
7 rather than a normal static property access like `obj.prop` on a normal
8 JavaScript `Object`.
9
10 This is useful for binding to `Proxy`s and some builtin DOM types that
11 dynamically intercept property accesses.
12
13 * `indexing_getter` corresponds to `obj[prop]` operation in JavaScript. The
14 function annotated must have a `this` receiver parameter, a single parameter
15 that is used for indexing into the receiver (`prop`), and a return type.
16
17 * `indexing_setter` corresponds to the `obj[prop] = val` operation in
18 JavaScript. The function annotated must have a `this` receiver parameter, a
19 parameter for indexing into the receiver (`prop`), and a value parameter
20 (`val`).
21
22 * `indexing_deleter` corresponds to `delete obj[prop]` operation in
23 JavaScript. The function annotated must have a `this` receiver and a single
24 parameter for indexing into the receiver (`prop`).
25
26 These must always be used in conjunction with the `structural` and `method`
27 flags.
28
29 For example, consider this JavaScript snippet that uses `Proxy`:
30
31 ```js
32 const foo = new Proxy({}, {
33 get(obj, prop) {
34 return prop in obj ? obj[prop] : prop.length;
35 },
36 set(obj, prop, value) {
37 obj[prop] = value;
38 },
39 deleteProperty(obj, prop) {
40 delete obj[prop];
41 },
42 });
43
44 foo.ten;
45 // 3
46
47 foo.ten = 10;
48 foo.ten;
49 // 10
50
51 delete foo.ten;
52 foo.ten;
53 // 3
54 ```
55
56 To bind that in `wasm-bindgen` in Rust, we would use the `indexing_*` attributes
57 on methods:
58
59 ```rust
60 #[wasm_bindgen]
61 extern "C" {
62 type Foo;
63 static foo: Foo;
64
65 #[wasm_bindgen(method, structural, indexing_getter)]
66 fn get(this: &Foo, prop: &str) -> u32;
67
68 #[wasm_bindgen(method, structural, indexing_setter)]
69 fn set(this: &Foo, prop: &str, val: u32);
70
71 #[wasm_bindgen(method, structural, indexing_deleter)]
72 fn delete(this: &Foo, prop: &str);
73 }
74
75 assert_eq!(foo.get("ten"), 3);
76
77 foo.set("ten", 10);
78 assert_eq!(foo.get("ten"), 10);
79
80 foo.delete("ten");
81 assert_eq!(foo.get("ten"), 3);
82 ```