Signal
A signal is a wrapper around a value that can notify interested consumers when that value changes
Value:
<!-- Signals automatically update the HTML --> <mc-textfield label="Type something" value="${page.basicBind}" oninput="page.basicBind.value = this.value" ></mc-textfield> <div>Value: ${page.basicBind}</div> <mc-button onclick="page.updateValue()">Set value to Updated</mc-button>
import { Component, Signal } from '@thewebformula/lithe'; import htmlTemplate from './page.html'; export default class extends Component { static title = 'Signal'; static htmlTemplate = htmlTemplate; basicBind = new Signal(''); constructor() { super(); } updateValue() { // HTML will automatically update this.basicBind.value = 'Updated'; } }
// quick example of using Signal, Compute, and effect import { Component, Signal, Compute, effect } from '@thewebformula/lithe'; import htmlTemplate from './page.html'; export default class extends Component { static title = 'Signal Compute effect'; static htmlTemplate = htmlTemplate; one = new Signal(1); // Compute will run when first created two = new Compute(() => { return this.one.value * 2; }); constructor() { super(); // runs when any signals or computes contained inside change // effect will run when first created const dispose = effect(() => { if (this.two > 10) { // do some work } }); // dispose effect dispose(); } }
Compute
Compute provides a way to interact with multiple signals to provide a single value
Value: 2
<!-- Computes automatically update the HTML --> <mc-textfield type="number" label="Type something" value="${page.number}" oninput="page.number.value = this.value"> </mc-textfield> <div>Value: ${page.numberTimesTwo}</div>
import { Component, Signal, Compute } from '@thewebformula/lithe'; import html from './page.html'; export default class extends Component { static title = 'Compute'; static htmlTemplate = html; number = new Signal(1); // Compute will run when first created numberTimesTwo = new Compute(() => { return this.number.value * 2; }); constructor() { super(); } }
Effect
Effects allows you to run code based on any changes for signals or computes it contains. The difference between effect and compute
is that effects do not return values.
import { Component, Signal, effect } from '@thewebformula/lithe'; import html from './page.html'; export default class extends Component { static title = 'Effect'; static htmlTemplate = html; one = new Signal(1); two = new Signal(2); constructor() { super(); // runs when any signals or computes contained inside change // effect will run when first created const dispose = effect(() => { if (this.one.value < this.two.value) { // do some work } }); // dispose effect dispose(); } }