Reputation: 740
<script>
let count = 0;
function handleClick() {
count += 1;
}
$: {
console.log('test'); // it is called once
// console.log(count); it is called every time the count is changed
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
I just wondered that how does svelte know what states is changed the dollar sign refers?
Svelte parses the code for that?
Upvotes: 2
Views: 1153
Reputation: 184534
Svelte parses the code for that?
Yes, changes to state cause values to be invalidated and on update reactive statements are called if they contain any invalidated values. If you look at the compiled output, you will find something like this:
function handleClick() {
$$invalidate(0, count += 1);
}
$$self.$$.update = () => {
if ($$self.$$.dirty & /*count*/ 1) {
$: {
console.log(count);
}
}
};
Upvotes: 4