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
docs: improve function bindings documentation with examples
- Added a hopefully clearer explanation of what function bindings are that is more approachable for newcomers
- Included practical examples for common use cases
Copy file name to clipboardExpand all lines: documentation/docs/03-template-syntax/12-bind.md
+81-1Lines changed: 81 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -19,7 +19,33 @@ Most bindings are _two-way_, meaning that changes to the value will affect the e
19
19
20
20
## Function bindings
21
21
22
-
You can also use `bind:property={get, set}`, where `get` and `set` are functions, allowing you to perform validation and transformation:
22
+
Function bindings allow you to define custom getter and setter logic while keeping the clean `bind:` syntax. Instead of just binding directly to a variable, you provide two functions: one to get the value, and one to set it.
23
+
24
+
```svelte
25
+
<input bind:value={
26
+
() => value, // getter
27
+
(v) => { value = v; } // setter
28
+
} />
29
+
```
30
+
31
+
Function bindings can act as "interceptors" for your data flow, allowing you to add custom logic when values are get or set:
32
+
33
+
```svelte
34
+
<Input bind:value={
35
+
() => name,
36
+
(v) => {
37
+
// Custom logic here!
38
+
name = v;
39
+
}
40
+
} />
41
+
```
42
+
43
+
This allows you to perform validation and transformations on inputs:
44
+
45
+
46
+
### Practical examples
47
+
48
+
#### Lowercase input
23
49
24
50
```svelte
25
51
<input bind:value={
@@ -28,6 +54,60 @@ You can also use `bind:property={get, set}`, where `get` and `set` are functions
28
54
/>
29
55
```
30
56
57
+
#### Format-as-you-type phone number
58
+
59
+
```svelte
60
+
<script>
61
+
let phoneNumber = $state('');
62
+
63
+
function formatPhone(value) {
64
+
// Remove all non-digits
65
+
const digits = value.replace(/\D/g, '');
66
+
67
+
// Format as (XXX) XXX-XXXX
68
+
if (digits.length <= 3) return digits;
69
+
if (digits.length <= 6) return `(${digits.slice(0, 3)}) ${digits.slice(3)}`;
0 commit comments