I was reading the doc, and after tweaking its sample code, I managed to get compiler barked at me about cyclic dependencies like this:
<script>
let count = 0;
$: double = count * 2;
$: if (double >= 20) {
alert(`count is dangerously high!`);
count = 9;
}
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
I asked on discord how to fix it, and people suggested that I should hide the dependencies from the compiler like this:
<script>
let count = 0;
$: double = count * 2;
function resetCount() {
count = 9;
}
$: if (double >= 20) {
alert(`count is dangerously high!`);
resetCount();
}
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
It works, but I got a couple questions:
- Battling with the compiler doesn't sound right to me, is there any other better ways to fix this?
- A more general question is that does cyclic dependencies happen quite often to people who have written large amount of svelte code? Is it normal or it usually signals a bad design?
Thanks.