What are Signals?
Signals are points of data located somewhere within the DOM. When a signal's value changes, the value in the DOM will reflect the change automatically.
Put plainly, signals allow us to bypass using document.querySelector
and related methods to handle DOM updates.
Signals allow to go from a fine-grained updates like this:
1<script>
2 let button = document.getElementById('btn');
3 button.addEventListener('click', () => {
4 let text = document.getElementById('text');
5 if (text.classList.contains('text-blue-500')) {
6 text.classList.remove('text-blue-500');
7 text.classList.add('text-red-500');
8 } else {
9 text.classList.remove('text-red-500');
10 text.classList.add('text-blue-500');
11 }
12 });
13</script>
14
15<button id='btn'>Click!</button>
16<p id='text' class="text-blue-500">Change my color by clicking</p>
To a more reactive model like this:
1 <script>
2 staci.set('colorClass', 'text-blue-500')
3 staci.event('changeColor', () => {
4 let [color, setColor] = staci.get('colorClass')
5 if (color == 'text-blue-500') {
6 setColor('text-red-500')
7 } else {
8 setColor('text-blue-500')
9 }
10 })
11 </script>
12
13 <button st-click='changeColor'>Click!</button>
14 <p class="{| colorClass |}">Change my color by clicking</p>
Creating a Signal
To create a signal:
1<script>
2 staci.set("count", 0)
3</script>
Mounting a Signal Within the DOM
To use the signal's value within the DOM, use the <st-signal>
custom element.
1<script>
2 staci.set("count", 0)
3</script>
4<p>
5 <st-signal>{| count |}</st-signal>
6</p>
<st-signal>
is used to ensure the elements value does not flicker placeholders {{}}
prior to staci
loading. Also, <st-signal>
isolates the value from the rest of the text in the elements body so it is more confidently updated.
Mounting a Signal Within an Attribute
To use a signal's value within an element's attribut, do this:
1<script>
2 staci.set("display", "hidden")
3</script>
4<p class="{| display |}">I am hidden!</p>