Spanish Total.js
English
Documentation For AI agents
Contents

Using components

How to place components on a page, configure them, find them and call their methods.

.md GitHub
On this page

A component is a reusable widget declared once and placed on the page with the <ui-component> element. This guide covers how to use existing components. To write your own, read Creating components.

Adding a component

<ui-component name="label" config="text:Hello"></ui-component>
<ui-component name="label" path="user.name"></ui-component>
<ui-component name="label" path="user.city" default="'Bratislava'"></ui-component>
AttributeDescription
nameThe name of the component
pathThe path of the value that the component works with. Components without a value do not need it
configThe configuration of this instance
defaultA JavaScript expression that fills the model when the value is null or undefined at startup
sourceThe URL to download the component from

In the example above, the third component writes Bratislava to user.city because the model has no value there. A string in default needs its own quotes.

Components work in HTML that you add later. The library initializes each <ui-component> element when it appears on the page.

Downloading components

When no component with the given name is declared at the moment the element initializes, the library downloads it. The address comes from DEF.fallback, which is https://cdn.componentator.com/j-{0}.html by default. The source attribute sets the address for one element.

<ui-component name="chart" path="stats.sales"></ui-component>
<ui-component name="gauge" source="/components/gauge.html"></ui-component>

The first element requests https://cdn.componentator.com/j-chart.html and the second requests /components/gauge.html. To load components from your own server, change the pattern:

DEF.fallback = '/components/{0}.html';

Configuration

The config attribute contains pairs in the form key:value separated by semicolons. Numbers and the words true and false are converted to their types. Write a literal semicolon as \; and a colon as \: in a value.

<ui-component name="box" config="title:Orders\: open;limit:10;ratio:0.5;active:true;note:a\;b"></ui-component>
COMPONENT('box', 'limit:5;color:red', function(self, config) {
    self.make = function() {
        console.log(config);
    };
});
{"limit":10,"color":"red","title":"Orders: open","ratio":0.5,"active":true,"note":"a;b"}

The result combines the defaults of the component with the values of the element.

Special keys

These keys are processed by the library and work with every component:

KeyDescription
$idSets the identifier of the instance
$classAdds CSS classes to the element
$assignStores the instance at a path
$initCalls a function when the component is initialized. The argument is the instance
$setterCalls a function each time the value changes. Arguments: value, path, flags
=keyReads the value of the configuration key key from a path and follows its changes
<ui-component name="box" path="form.name" config="$id:mainbox;$class:highlighted;$assign:refs.box;$init:FUNC.boxready;$setter:FUNC.boxchanged"></ui-component>
FUNC.boxready = function(component) {
    console.log('ready', component.id);
};

FUNC.boxchanged = function(value, path, flags) {
    console.log('value', value);
};
ON('ready', function() {
    SET('form.name', 'Ana');
    console.log(refs.box.name, FIND('#mainbox').element.attr('class'));
});
ready mainbox
value undefined
value Ana
box highlighted

A configuration key linked to a path changes together with the model:

<ui-component name="title" config="=text:settings.title"></ui-component>
COMPONENT('title', function(self) {
    self.configure = function(key, value) {
        if (key === 'text')
            self.text(value);
    };
});

SET('settings.title', 'First');
ON('ready', function() {
    SET('settings.title', 'Second');
});

The component shows First and then Second.

Configuring many components at once

CONFIG(selector, config) applies a configuration to existing components and to those created later. The selector is a component name, several names separated by commas, or * for all components.

<ui-component name="box"></ui-component>
<ui-component name="box" config="color:blue"></ui-component>
CONFIG('box', 'size:large');
ON('ready', function() {
    CONFIG('box', { color: 'green' });
    console.log(FIND('box', true).map(com => com.config.color));
});
new red large
new blue large
["green","green"]

Finding components

CodeReturns
FIND('name')The first component with this name
FIND('#id')The component with this identifier
FIND('.path')The first component on this path
FIND('name', true)An array of all matches
COMPONENTS('path')An array of the components on the path. See flags for filters
$(element).component()The component of the element or of its closest parent

FIND() returns only initialized components. Run your code in the ready event to be sure that the components on the page exist.

Calling methods

SETTER('selector/method', [a], [b], [c], [d]) calls a method on all matching components. The selector is a component name, #id, or * for all components that have the method.

<ui-component id="first" name="counter" path="stats.a" config="$id:visits"></ui-component>
<ui-component name="counter" path="stats.b"></ui-component>
COMPONENT('counter', function(self) {
    self.add = function(count) {
        self.set((self.get() || 0) + count);
    };
});
ON('ready', function() {
    SETTER('#visits/add', 2);
    console.log(stats.a);

    SETTER('counter/add', 1);
    console.log(stats.a, stats.b);

    console.log(FIND('counter').path.toString());
    console.log(FIND('counter', true).length);
    console.log(FIND('#visits').path.toString());
    console.log(FIND('.stats.b').path.toString());
    console.log($('#first').component().id);
});
2
3 1
stats.a
2
stats.a
stats.b
visits

Add the flag @important when the component may not exist yet. The call is repeated until the component appears:

SETTER('notify/show @important', 'Saved');

setTimeout(function() {
    COMPONENT('notify', function(self) {
        self.show = message => console.log(message);
    });
    $(document.body).append('<ui-component name="notify"></ui-component>');
}, 100);
Saved

Lazy components

With the prefix LAZY, a component is created at the first SETTER() call that targets it. This suits dialogs and other parts that many visitors never open.

<ui-component name="LAZY dialog"></ui-component>
COMPONENT('dialog', function(self) {
    self.make = () => console.log('created');
    self.open = title => console.log('open', title);
});
ON('ready', function() {
    SETTER('dialog/open', 'Settings');
});
created
open Settings

State

The library keeps the state of each component in its configuration and reflects it in CSS classes on the element:

CSS classConfiguration keyMeaning
ui-touchedtouchedThe user has interacted with the component
ui-modifiedmodifiedThe user has changed the value
ui-invalidinvalidThe value did not pass the validation of the component
ui-disableddisabledThe component is disabled
<ui-component id="a" name="field" path="form.name" config="required:true"></ui-component>
<ui-component id="b" name="field" path="form.note" config="disabled:true"></ui-component>

At startup, the first component has the class ui-invalid because its value is missing and the second has ui-disabled. Read more in Forms and validation.

Removing components

Remove the element from the page like any other element. The library releases removed components once a minute, and FREE() does it immediately. The destroy delegate of the component runs at that moment.

ON('ready', function() {
    $('#area').empty();
    FREE();
    console.log(FIND('box', true).length);

    $('#area').html('<ui-component name="box"></ui-component>');
});

FIND('name').remove() removes one component and its element immediately.

Made in Europe