Signal

A signal is a reactive primitive which allows us to react to it changes, every piece of code who depends on a signal can get updated automatically, this is the core concept used inside VistaJS, wich allows it to update the HTML template when a signal its binded to it, let's learn it a little bit more about signal.

Binding a signal to a template

Component('app-counter', () => {
   const counter = signal(0);
   
   return () => html`<button>${counter()}</button>`
})

As result, we are going to have:

<app-counter>
    <button>0</button>
</app-counter>

Reacting to signal changes

This is quite simple, just set a new value to the signal

Component('app-counter', () => {
   const counter = signal(0);
   
   const handleCounter = () => {
     counter.set(1);
   }
   
   return () => html`<button onclick=${handleCounter}>${counter()}</button>`
})

When the button gets clicked, we are going to see the following in the DOM:

You can even increment the value based on the current one, such as:

So, when the button gets clicked, the fist time we get:

Then, by clicking the second time, we get 2 and so on.

Last updated