8

Creating a web component using svelte, I need to run some code when an attribute of the component is changed.

What I have come up with is the following pattern.

<script>
    export let test = "default value";

    $: {
        testIsChanged(test);
    }

    function testIsChanged(newValue) {
        console.log(newValue);
    }
</script>

The value of test is {test} 

Is this the way to do it? Or am I missing something?

Tamas
  • 10,953
  • 13
  • 47
  • 77
PEtter
  • 806
  • 9
  • 22
  • 1
    More simply, just `$: console.log(test)` — https://svelte.dev/repl/99fc7cf6e45c41859eb27146b99b5af3?version=3.12.1 – Rich Harris Sep 17 '19 at 17:33
  • Just to be sure i do not miss something. @RichHarris, what i want to do in my function is loading data from server :D, then this would be the way. Would it be an idea to actually propagate the 'on attribute change' that is listened to in the custom control to a function inside the control, by naming convension maybe? I will put this as an issue in github.. – PEtter Sep 18 '19 at 06:20
  • After thinking a bit more.. no need for it... – PEtter Sep 18 '19 at 07:08
  • I know nobody wants to correct RICH HARRIS, but, don't you mean "More simply, just `$: testIsChanged(test);` ? – bjscollura Mar 14 '23 at 15:39

2 Answers2

3

That will indeed work, as you can see in this REPL

Antony Jones
  • 2,387
  • 1
  • 15
  • 18
1

The example above with just $: will invoke with any state changes being observed for all variables changing, not just the one you're interested in. (Includes other events like subscribe to Svelte store changes.).

See the slight different syntax below, placing the $:variable && function you want to invoke on change lets you achieve tracking state change without false triggers from other events.

<script>
    export let test = "default value";

    $: test && testIsChanged();

    const testIsChanged = () => {
        console.log(newValue);
    }
</script>
RyvDx
  • 21
  • 4
  • 2
    Notice that the `&&` checks for falsy values, so if `test` was for example `0` or an empty string here, the function wouldn't run https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND – Corrl Mar 09 '23 at 19:48