Skip to content

Allow spreading function bindings #16086

@jackgdll

Description

@jackgdll

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} />

Playground

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions