Search code examples
sveltesvelte-3svelte-component

Make two variables reactive both ways


I want to make two variables reactive both ways. That means, if i change, lets say variable a, then i want variable b to change specified by some defined function, and if i change variable b, then i want a to change by the same function, but inversly:

$: b = 2 * a
$: a = 1/2 * b // This lines makes these dependencies cyclical.

I have this REPL to show what i want. How can i achieve this? (Ideally by smart svelte assignments, as the $-sign, but "on:input" solutions will also work.)


Solution

  • We can actually simplify without using $: for this case, How about?

    <script>
        let a = 1;
    </script>
    
    <input type="number" bind:value={a} > <br>
    
    <input type="number" value={2 * a} on:change={(e) => a = 1/2 * e.target.value}>