-
- Notifications
You must be signed in to change notification settings - Fork 4.7k
Milestone
Description
Describe the problem
Function bindings are awesome, but you need to pass the getter and setter explicitly: bind:value={get, set}.
This syntax can become verbose and repetitive, especially when the getter and setter are returned together from a helper function.
For example, say you want to display a default value in an input but only set it back to the bound state if it was changed from the default. This can be achieved with the following utility:
export function bindWithDefault<T>(get: () => T, set: (value: T) => void, defaultValue: T) { return [ () => get() ?? defaultValue, (v: T) => { if (get() !== undefined || v !== defaultValue) { set(v); } } ] }However, using this utility isn't very ergonomic for the reasons stated above:
<script> let name = $state(undefined); const [get, set] = bindWithDefault( () => name, v => (name = v), 'world' ); </script> <h1>Hello {name}!</h1> <input bind:value={get, set} />Describe the proposed solution
It would be nice to be able to spread in a tuple of functions, or an object with a get and/or set method instead of needing to declare them in the script or in a {@const ...} tag.
<input bind:value={...bindWithDefault( () => name, (v) => (name = v), "world" )} />Importance
nice to have
brunnerh, rChaoz, Ocean-OS, felixniland, TortoiseWrath and 2 more
Metadata
Metadata
Assignees
Labels
No labels