Variable
The variable() Factory
The Cog library is designed with simplicity in mind and thus provides a single API, the variable method (if we exclude the render method).
variable is a function that creates a new reactive variable. It is used to create a state variable within the state object of the Cog library that you can later use in your HTML. It takes a name and an initial value as arguments, and adds an entry to the state object with the given name and value.
const foo = variable("foo", "bar"); // state = { foo: "bar" }
The function returns an object with a set() method and a value getter, but also a setter in case you prefer to use it that way. It will also define a state variable "foo" that you can use in your HTML to retrieve it's value, like {{ foo }}.
set()
The set method allows you to update the value of the state variable from your JavaScript code. It takes a new value as an argument, and updates the state variable with this new value.
const foo = variable("foo", "bar");
foo.set("baz"); // state = { foo: "baz" }
When a state variable's value is updated using the set method, the UI is re-rendered, and any expressions referencing that variable are re-evaluated with the new value. This design allows the expressions in your HTML to automatically update whenever the state changes.
value (getter/setter)
The value getter allows you to retrieve the current value of the state variable from your JavaScript code.
const foo = variable("foo", "bar");
console.log(foo.value); // "bar"
The value setter allows you to update the value of the state variable directly. It's an alternative to the set() method.
const foo = variable("foo", "bar");
foo.value = "baz"; // state = { foo: "baz" }
Just like the set() method, when you change a state variable's value using the value setter, the UI is automatically re-rendered.