sveltesveltekit

How to monitor a variable and run a function every time the variable changes?


It will be like the on:change event.

I am not using this event because in some svelte libraries this event is not emitted, and the implication is to use binding and $.

However, it seems that Svelte doesn't have a clean syntax for it.

I can only think of something like

$: {
    if (variable) {
        doSomething();
    }
}

where every time variable's value changes, doSomething() will run.

But the use of if statement is weird.. What if variable is a boolean? This way the function won't run when the variable's value is false.

The idea is to run the function every time the variable's value changes, no matter what the new value actually is.

I also tried

$: doSomething(variable);

It works, but it is also weird because the function doSomething may not need an argument. In this case, the argument is purely for adding the variable as a dependency of this $ syntax...

Also tried the answer in https://stackoverflow.com/a/56987526/11752443, but this one simply doesn't work. And it is not mentioned in the doc (https://stackoverflow.com/a/56987526/11752443) either.

Thanks in advance!


Solution

  • The solution suggested by Rich Harris does seem to work:

    $: variable, doSomething()
    

    Working example: https://svelte.dev/repl/c25bdd71c9764f1f809bd35737fbaeb9?version=3.53.1