You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: documentation/docs/02-runes/02-$state.md
+48-7Lines changed: 48 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -36,12 +36,7 @@ let todos = $state([
36
36
...modifying an individual todo's property will trigger updates to anything in your UI that depends on that specific property:
37
37
38
38
```js
39
-
// @filename: ambient.d.ts
40
-
declare global {
41
-
const todos:Array<{ done:boolean, text:string }>
42
-
}
43
-
44
-
// @filename: index.js
39
+
let todos = [{ done:false, text:'add more todos' }];
45
40
// ---cut---
46
41
todos[0].done=!todos[0].done;
47
42
```
@@ -64,6 +59,17 @@ todos.push({
64
59
65
60
> [!NOTE] When you update properties of proxies, the original object is _not_ mutated.
66
61
62
+
Note that if you destructure a reactive value, the references are not reactive — as in normal JavaScript, they are evaluated at the point of destructuring:
63
+
64
+
```js
65
+
let todos = [{ done:false, text:'add more todos' }];
66
+
// ---cut---
67
+
let { done, text } = todos[0];
68
+
69
+
// this will not affect the value of `done`
70
+
todos[0].done=!todos[0].done;
71
+
```
72
+
67
73
### Classes
68
74
69
75
You can also use `$state` in class fields (whether public or private):
@@ -85,7 +91,42 @@ class Todo {
85
91
}
86
92
```
87
93
88
-
> [!NOTE] The compiler transforms `done` and `text` into `get`/`set` methods on the class prototype referencing private fields.
94
+
> [!NOTE] The compiler transforms `done` and `text` into `get`/`set` methods on the class prototype referencing private fields. This means the properties are not enumerable.
95
+
96
+
When calling methods in JavaScript, the value of [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) matters. This won't work, because `this` inside the `reset` method will be the `<button>` rather than the `Todo`:
97
+
98
+
```svelte
99
+
<button onclick={todo.reset}>
100
+
reset
101
+
</button>
102
+
```
103
+
104
+
You can either use an inline function...
105
+
106
+
```svelte
107
+
<button onclick=+++{() => todo.reset()}>+++
108
+
reset
109
+
</button>
110
+
```
111
+
112
+
...or use an arrow function in the class definition:
0 commit comments