Spanish Total.js
English
Documentation For AI agents
Contents

Creating components

How to declare your own components, handle values and configuration, validate input and clean up.

.md GitHub
On this page

A component joins HTML, behaviour and a value from the model into one reusable widget. You declare it once with COMPONENT() and use it on the page as described in Using components.

Declaring a component

COMPONENT(name, [config], callback, [dependencies], [css]);
ArgumentTypeDescription
nameStringThe name used in <ui-component name="...">
configStringThe default configuration in the form key:value;key:value
callbackFunctionRuns for each instance with the arguments self, config and cls
dependenciesString or ArrayResources to load ahead of the initialization. A string can list several URLs separated by commas
cssStringThe CSS of the component
<ui-component name="hello" config="name:Ana"></ui-component>
COMPONENT('hello', 'name:World', function(self, config, cls) {
    self.make = function() {
        self.aclass(cls);
        self.text('Hello ' + config.name);
    };
});

The rendered element:

<ui-component name="hello" config="name:Ana" class="ui-hello">Hello Ana</ui-component>

The callback receives:

  • self, the component instance
  • config, the merged configuration of the instance
  • cls, the CSS class name of the component in the form ui-name. The library does not add it to the element, so call self.aclass(cls)

Declare components while the page loads. A name that is unknown when its element initializes is downloaded from the CDN.

Lifecycle

You define the behaviour of a component by assigning functions, called delegates, to self. The library calls them in this order:

<ui-component name="demo" path="app.value"></ui-component>
<ui-component name="demo" path="app.value"></ui-component>
COMPONENT('demo', 'color:red', function(self, config) {
    console.log('declaration');
    self.init = () => console.log('init');
    self.make = () => console.log('make');
    self.configure = (key, value, init) => console.log('configure', key, value, init);
    self.setter = (value, path, flags) => console.log('setter', value, path, flags);
    self.validate = () => true;
    self.state = () => console.log('state');
    self.done = () => console.log('done');
});

SET('app.value', 1);
declaration
init
make
configure color red true
setter 1 app.value {"init":1}
configure invalid false undefined
state
done
declaration
make
configure color red true
setter 1 app.value {"init":1}
configure invalid false undefined
state
done
DelegateWhen it runs
self.init()Once for the component type, on its first instance
self.make()Once for each instance. Create the HTML here
self.configure(key, value, init)For each configuration key at startup, with init set to true, and at each later change
self.setter(value, path, flags)When the value in the model changes
self.setter2(value, path, flags)After setter, also for values written by the component itself
self.validate(value)After each change of the value. It decides if the value is valid
self.state()When the library updates the touched, modified, invalid or disabled state
self.done()Once for each instance, at the end of the initialization
self.destroy()When the component is removed

The configuration keys that the library maintains, such as invalid, also go through configure.

Useful properties

PropertyDescription
self.elementThe element as a jQuery object
self.domThe DOM element
self.configThe configuration
self.pathThe path of the component. Use self.path.toString() to get a string
self.nameThe name of the component
self.idThe identifier of the instance

The complete list is in the Component reference.

Receiving values

self.setter runs at startup and on each change of the value. The path argument contains the path that was changed, which can be a parent of the component's path. The flags argument contains the flags of the operation. The library adds init for the first call and refresh for self.refresh().

<ui-component name="badge" path="inbox.count"></ui-component>
COMPONENT('badge', function(self) {

    self.setter = function(value, path, flags) {
        self.text(value == null ? 'none' : value + ' new');
        console.log(self.text(), path, flags);
    };

});

SET('inbox.count', 3);
ON('ready', function() {
    SET('inbox.count', 5);
    SET('inbox @reload', { count: 7 });
    FIND('badge').refresh();
});
3 new inbox.count {"init":1}
5 new inbox.count {}
7 new inbox {"reload":1}
7 new inbox.count {"refresh":1}

A component without its own setter writes the value into the first input, select or textarea inside its element.

Sending values

MethodEffect
self.get()Reads the value from the model
self.set(value, [flags])Writes the value and calls the setters of all components on the path
self.modify(value, [flags])Marks the component as touched and modified, and then writes the value
self.rewrite(value, [flags])Writes the value without calling the setter of this component
<ui-component name="stepper" path="cart.quantity" config="step:2"></ui-component>
<p>Quantity: <ui-bind path="cart.quantity" config="text"></ui-bind></p>
COMPONENT('stepper', 'step:1', function(self, config) {

    self.make = function() {
        self.html('<button name="minus">-</button><b></b><button name="plus">+</button>');
        self.event('click', 'button', function() {
            var diff = this.name === 'plus' ? config.step : -config.step;
            self.modify((self.get() || 0) + diff);
        });
    };

    self.setter = function(value) {
        self.find('b').text(value);
    };

});

SET('cart.quantity', 4);

Clicking + changes the quantity from 4 to 6. The element receives the classes ui-touched and ui-modified, and the paragraph follows the model.

self.rewrite() suits components that already display the value they write. Their setter is skipped, while setter2 still runs:

<ui-component name="search" path="filter.query"></ui-component>
COMPONENT('search', function(self) {

    self.setter = value => console.log('setter', value);
    self.setter2 = value => console.log('setter2', value);

    self.write = function(value) {
        self.rewrite(value);
    };

});
ON('ready', function() {
    SET('filter.query', 'pen');
    FIND('search').write('book');
    console.log(filter.query);
});
setter pen
setter2 pen
setter2 book
book

Binding inputs

self.autobind20([delay]) connects the input, select and textarea elements inside the component to the model. It writes the value while the user types, after a delay of 200 milliseconds by default, and marks the component as touched and modified.

The value passes through these steps on its way to the model:

  1. The function registered with self.parser() changes the value.
  2. The configuration key type converts it. Supported types are number, currency, float, boolean, bool, date and datetime.

On its way to the input, the default setter passes the value through the function registered with self.formatter().

<ui-component name="input" path="order.count" config="type:number"></ui-component>
<ui-component name="input" path="order.code" config="upper:true"></ui-component>
COMPONENT('input', function(self, config) {

    self.make = function() {
        self.html('<input type="text" />');
        self.autobind20();
    };

    self.parser(function(path, value) {
        return config.upper ? value.toUpperCase() : value;
    });

    self.formatter(function(path, value) {
        return config.upper && value ? value.toLowerCase() : value;
    });

});

SET('order.code', 'ABC');

After typing 42 into the first input and xyz into the second, the model contains:

{"code":"XYZ","count":42}

The second input showed abc at startup, because the formatter converts the stored ABC for display. To process a value from your own widget in the same way, call self.getter(value).

Configuration

Read the configuration from the config object. Use self.configure to apply the values and to react to later changes. self.reconfigure() changes the configuration of a running component. It accepts a string or an object.

<ui-component name="textbox" path="form.name"></ui-component>
COMPONENT('textbox', 'maxlength:10', function(self, config) {
    self.make = function() {
        self.html('<input type="text" />');
    };
    self.configure = function(key, value) {
        if (key === 'maxlength')
            self.find('input').attr(key, value);
    };
});

EXTENSION('textbox', 'maxlength:5', function(self, config) {
    self.clear = () => self.set('');
});
ON('ready', function() {
    console.log(FIND('textbox').config.maxlength);
    console.log(typeof FIND('textbox').clear);

    FIND('textbox').reconfigure('maxlength:3');
    console.log(FIND('textbox').find('input').attr('maxlength'));

    FIND('textbox').reconfigure({ maxlength: 8 });
    console.log(FIND('textbox').find('input').attr('maxlength'));
});
5
function
3
8

EXTENSION(name, [config], callback) adds behaviour to a component that you did not write. It works for existing instances and for those created later. In the example above, it changes the default maxlength and adds the method clear().

Validation and state

self.validate returns true for a valid value. Return false or a string for an invalid one. A string is stored in config.invalid, so it can serve as the error message.

<ui-component id="pin" name="pin" path="login.pin"></ui-component>
COMPONENT('pin', function(self, config) {

    self.validate = function(value) {
        return value && value.length === 4 ? true : 'Enter 4 digits';
    };

    self.state = function() {
        self.text(config.invalid && config.touched ? config.invalid : 'OK or untouched');
    };

});
ON('ready', function() {
    var pin = FIND('pin');

    pin.touch();
    console.log(pin.config.touched, pin.config.invalid);

    SET('login.pin', '1234');
    console.log(pin.config.invalid);

    pin.reset();
    console.log(pin.config.touched);
});
1 Enter 4 digits
false
0
MethodEffect
self.touch()Marks the component as touched and validates it
self.change()Marks the component as touched and modified, and validates it
self.reset()Clears the touched and modified state and validates the component

Read the current state from config.touched, config.modified, config.invalid and config.disabled in self.state. The library maintains the CSS classes ui-touched, ui-modified, ui-invalid and ui-disabled for you.

Styles

The last argument of COMPONENT() contains the CSS. The word CLASS is replaced by the class name of the component.

<ui-component name="card"><b>Title</b></ui-component>
COMPONENT('card', '', function(self, config, cls) {
    self.make = () => self.aclass(cls);
}, null, '.CLASS { border: 1px solid #ccc; } .CLASS b { color: red; }');

The library adds this rule to the page:

.ui-card { border: 1px solid #ccc; } .ui-card b { color: red; }

Methods and commands

Each function that you assign to self is a public method, which others call with SETTER(). A command is a named action with any number of handlers, registered with self.command(name, callback) and executed on an instance with self.CMD(name, [a], [b], [c], [d]), or on every component that has it with the global CMD(name, [a], [b], [c], [d]).

<ui-component name="list" path="data.rows"></ui-component>
COMPONENT('list', function(self) {

    // A public method
    self.clear = function() {
        self.set([]);
    };

    // A named command, a command name can have several handlers
    self.command('highlight', index => console.log('first handler', index));
    self.command('highlight', index => console.log('second handler', index));

});

SET('data.rows', [1, 2, 3]);
ON('ready', function() {
    SETTER('list/clear');
    console.log(data.rows);

    FIND('list').CMD('highlight', 2);
});
[]
first handler 2
second handler 2

Events and watchers

MethodDescription
self.event(name, [selector], callback)Registers a DOM event on the element
self.on(name, callback)Registers a global event sent with EMIT()
self.watch(path, callback, [init])Watches a path of the model
self.watch(callback)Watches the path of the component
<ui-component name="status" path="app.state"></ui-component>
COMPONENT('status', function(self) {

    self.make = function() {

        // Any path of the model
        self.watch('app.user', function(value, flags, path) {
            console.log('user', value, path);
        });

        // The path of the component
        self.watch(value => console.log('own path', value));

        // A global event
        self.on('logout', reason => console.log('logout', reason));
    };

});
ON('ready', function() {
    SET('app.user', 'Ana');
    SET('app.state', 'online');
    EMIT('logout', 'timeout');
});
user Ana app.user
own path online
logout timeout

Cleaning up

Release timers and other resources in self.destroy:

<ui-component name="ticker"></ui-component>
COMPONENT('ticker', function(self) {

    var timer;

    self.make = function() {
        timer = setInterval(() => self.text(new Date().toISOString()), 1000);
    };

    self.destroy = function() {
        clearInterval(timer);
        console.log('stopped');
    };

});

Special kinds of components

MethodEffect
self.singleton()Allows one instance on the page. The library removes the elements of other instances
self.blind()The component does not react to changes in the model
self.readonly()The component only displays content. It has no setter, no getter and no validation
<ui-component name="toast"></ui-component>
<ui-component name="toast"></ui-component>
COMPONENT('toast', function(self) {
    self.singleton();
    self.make = () => console.log('created once');
});

The delegate make runs once and one <ui-component> element stays on the page.

<ui-component name="clock" path="app.time"></ui-component>
<ui-component name="logo" path="app.time"></ui-component>
COMPONENT('clock', function(self) {
    self.blind();
    self.setter = value => console.log('clock setter', value);
});

COMPONENT('logo', function(self) {
    self.readonly();
    self.make = () => self.text('Logo');
});
ON('ready', function() {
    SET('app.time', 1);
    console.log(FIND('logo').config.invalid);
});

After SET('app.time', 1), the clock component does not run its setter, and logo stays valid.

Dependencies

The fourth argument lists what a component needs. A string is a URL loaded with IMPORT(), and a function receives a next callback. The instance starts when all dependencies are ready.

<ui-component name="map"></ui-component>
COMPONENT('map', '', function(self) {
    self.make = () => console.log('ready to use', W.mapsdk);
}, [
    'https://example.com/maps.js',
    function(next) {
        W.mapsdk = 'loaded';
        next();
    }
]);
Made in Europe