-
Notifications
You must be signed in to change notification settings - Fork 0
Logic
Cardboard offers a set of methods for adding logic to your apps. Some logic is handled in the tag, and some logic is handled using the functions mentioned on this page, like each
.
Tag logic allows you to do things such as hiding, disabling, adding classes, styles, etc... in a reactive way.
const myElement = tag('div');
const isActive = state(true);
myElement.classIf(isActive, ['active', 'highlighted']);
myElement.hideIf(isActive);
See Manipulating Tags for a more detailed explanation.
When building interfaces you will often need to work with lists of data. So instead of having to manually add each item, you can use the each
function to do the job for you.
each
can work with a good old array, or with a Consumable<any[]>
. If you provide a Consumable
, the list will update whenever the Consumable
changes.
Let's look at the very simplest example, a static list, that will not change:
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
div(
each(colors, (color) =>
button(color).addStyle('color', color)
)
);
This code will add a button for each color to the div
. Note that if you change the colors array, the rendered content will stay the same. To update the content, you can by creating a dynamic list.
If you want the content to update when the content changes, you must provide an array Consumable (created with state
in the example below). By doing this, whenever the colors state changes, the content will be updated accordingly.
You can also use listState for better ergonomics.
Take a look at this example:
const colors = state(['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']);
const selectedColor = state('red');
div(
each(colors, (color) =>
button(color)
.addStyle('color', color)
.stylesIf(equalTo(selectedColor, color), { fontWeight: 'bold' });
)
);
There are a couple of differences with the static example:
- On one hand we create a
state
(aka Consumable) instead of a regular array. - We create another
state
for the selected color. - This allows us to use
logic
likestylesIf
in this case. We specify that, when the color is equal to the selectedColor, the text must be bold. This will happen each time the selected color is changed.
This is quite handy, we can then modify the colors, set the selectedColor, remove colors, etc...
You can add items to colors.value
yourself, but note that using push
and other methods will not work, you must assign a new value. Gladly Cardboard offers a few methods to handle this a bit better. So instead of having to do this:
colors.value = [...colors.value, newColor];
We can do this:
stateAdd(colors, 'black');
Take a look at the State Utilities page for more information.
This Wiki is a work in progress, it's just me doing everything around here :P
If you read this and have some free time, and want to spend it helping me with the wiki or anything else, you're more than welcome!