Is there any way to bind a state value and a bindable value in the same time in a component? #15006
Answered
by
david-plugge
tan-zhiheng
asked this question in
Q&A
-
BackgroudI want to creat a component that can be controled by other component throuth context. Codecomponent<script>
import {getInputState} from '$lib/input.state.svelte';
let { value = $bindable(), ...props } = $props();
const {inputValue} = getInputContext()
inputValue.value = value // <= I want to control in inputContext like set value to empty string, but it can be only read value in this way.
</script>
<input bind:value={value} {...props} /> parent component<script>
import {setInputContext} from '$lib/input.state.svelte';
const {resetInputValue} = setInputContext()
resetInputValue() // <= not work
</script>
... other component $lib/input.state.svelte.jsexport class InputState {
inputValue = $state({
value: '',
});
resetInputValue = ()=>{
this.inputValue.value = ''
}
}
const CONTEXT_KEY = Symbol('multi-selector');
export function setInputState() {
return setContext(CONTEXT_KEY, new InputState());
}
export function getInputState() {
return getContext(CONTEXT_KEY);
} |
Beta Was this translation helpful? Give feedback.
Answered by
david-plugge
Jan 14, 2025
Replies: 1 comment 1 reply
-
Runes or signals in general are not designed for two way bindings. You want to have a single source of truth. You can take a look at how bits-ui does it using a |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
tan-zhiheng
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Runes or signals in general are not designed for two way bindings. You want to have a single source of truth. You can take a look at how bits-ui does it using a
box
: https://github.com/huntabyte/bits-ui/blob/edc7eba4f47d8be1643f2ef590c9196b649c6686/packages/bits-ui/src/lib/bits/select/components/select.svelte#L33