---
title: Introduction
project: jComponent V20
version: 20.015
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/guides/introduction/
updated: 2026-11-18T13:55:29.124Z
---
# Introduction
> What jComponent is, the ideas it is built on and what the library includes.
jComponent is the client-side UI library of Total.js. You keep the data of your application in plain JavaScript objects, address that data with string paths and connect it to the page with custom HTML elements. When a value changes through the library, every element that depends on it updates itself.
There is no build step. A page needs one script and one stylesheet.
## A first look
```html
Hello
```
```js
SET('common.user', 'Ana');
// Later, from any place in your code:
setTimeout(function() {
SET('common.user', 'Peter');
}, 500);
```
The page shows `Hello Ana` and, half a second later, `Hello Peter`. The code never touches the DOM: it writes a value to the path `common.user`, and the `` element that listens to this path renders it.
## The building blocks
| Concept | What it does | Guide |
| --- | --- | --- |
| Path | A string such as `app.user.name` that addresses a value in the global `window` object | [Paths](../paths/) |
| Flag | A word such as `@change` added to a path that changes how an operation behaves | [Flags and path modifiers](../flags/) |
| `` | An element that renders a value of the model into the page | [Data binding](../data-binding/) |
| Component | A reusable widget that reads a value from a path and can write it back | [Using components](../using-components/), [Creating components](../creating-components/) |
| Plugin | A block of application logic with its own part of the model | [Plugins](../plugins/) |
## How data flows
1. Your code calls `SET()`, or a component writes a value that the user entered.
2. The library stores the value at the path, inside a normal JavaScript object.
3. The library notifies everything that depends on the path: components, `` elements and watchers registered with `WATCH()`.
4. Each of them updates its own part of the page.
Because the model is a plain object, you can read it at any time, for example `app.user.name` in the browser console.
## What the library includes
The file `spa.min@20.js` is a single bundle with everything a page needs:
- jComponent itself
- jQuery 3.7.1, available as `$`
- [Tangular](../tangular/), the template engine
- [Routing](../routing/) for single-page applications, with `ROUTE()`, `REDIRECT()` and `NAV`
The file `spa.min@20.css` contains a CSS reset, a responsive grid and helper classes such as `hidden` and `invisible`.
## Where to go next
Follow [Getting started](../getting-started/) to build a working page with a custom component and bound data. All functions are listed in the [global functions](../../reference/globals/) reference.
---
title: Getting started
project: jComponent V20
version: 20.015
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/guides/getting-started/
updated: 2026-11-18T18:15:21.747Z
---
# Getting started
> Build a working page with bound data and a custom component, starting from an empty file.
This guide takes you from an empty file to a working page with a custom input component and data bound to it. You need a text editor and a browser.
## Create the page
Create a file named `index.html` and load the library from the CDN:
```html
My first page
```
All the following code goes inside ``. Open the file directly in the browser to see the result.
## Show a value
Write a value to the model with `SET()` and display it with a `` element:
```html
Hello
```
The page shows `Hello Ana`.
- `SET('app.name', 'Ana')` creates the global object `app` and stores the value in `app.name`.
- `path` tells `` which value to listen to.
- `config="text"` tells it to render the value as text.
Every later `SET('app.name', ...)` updates the heading. Read more in [Paths](../paths/) and [Data binding](../data-binding/).
## Create a component
A component is a reusable widget. Declare it once with `COMPONENT()` and place it on the page with ``. Replace the content of `` with this code:
```html
Hello
```
Type into the field and the heading follows your text. Clear the field and the heading shows `Hello stranger`, because `empty:stranger` in the `` configuration sets the text for an empty value.
Here is what each part of the declaration does:
| Code | Purpose |
| --- | --- |
| `'textbox'` | The name used in `` |
| `'label:Name'` | The default configuration, which the `config` attribute can override |
| `self.make` | Runs once for each instance and creates its HTML |
| `self.aclass(cls)` | Adds the CSS class `ui-textbox` to the element |
| `self.autobind20()` | Writes the content of the input to the model while the user types |
| `self.configure` | Runs for each configuration key |
| `self.validate` | Says if the current value is valid. The library then adds or removes the class `ui-invalid` |
| The last argument | CSS of the component, where `CLASS` stands for `ui-textbox` |
The component does not define how to show the value in the input. When a component has no `setter` of its own, the library writes the value into the first `input`, `select` or `textarea` inside the component.
## Run code from a button
Elements with the class `exec` call the function named in their `data-exec` attribute when they are clicked. Add a button that clears the model:
```html
Hello
Clear
```
Then add the function to the script, above the `SET()` call:
```js
FUNC.clear = function() {
SET('app.name', '');
};
```
`FUNC` is an empty global object meant for your own functions. The click changes only the model. The input, the heading and the validation state all follow.
## The complete page
```html
My first page
Hello
Clear
```
## If something does not work
- **The component stays empty.** Check that the `name` attribute matches the name in `COMPONENT()`. For an unknown name, the library tries to download the component from the CDN and writes `jComponent: Downloading "name" component.` to the console.
- **The value does not change on the page.** Change the model with `SET()`. A direct assignment such as `app.name = 'Ana'` does not notify anybody until you call `UPD('app.name')`.
## Next steps
- [Paths](../paths/) explains how to address and change data.
- [Data binding](../data-binding/) shows everything `` can do.
- [Creating components](../creating-components/) covers the whole component API.
---
title: Migrating from jComponent 19
project: jComponent V20
version: 20.015
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/guides/migrating-from-v19/
updated: 2026-11-22T18:42:02.302Z
---
# Migrating from jComponent 19
> Replace every removed or changed jComponent 19 API with its jComponent 20 equivalent, including the changes that fail without an error.
This guide moves an application from jComponent 19 to jComponent 20.015. It shows the replacement for each function, attribute and setting that was removed or changed, and it marks the changes that give no error in the browser console, because those are the ones a quick test misses.
## Update the CDN files
Replace both files. The bundle still contains jQuery, Tangular and the routing functions, so nothing else has to be loaded.
| jComponent 19 | jComponent 20 |
| --- | --- |
| `https://cdn.componentator.com/spa.min@19.js` | `https://cdn.componentator.com/spa.min@20.js` |
| `https://cdn.componentator.com/spa.min@19.css` | `https://cdn.componentator.com/spa.min@20.css` |
## Recommended order of work
1. Replace the CDN files and open the application with the browser console visible.
2. Change the markup first: `data---`, `data-bind` and `data-scope` elements are ignored, so nothing else can be tested until they are converted.
3. Search the code for the patterns in [Changes that fail silently](#changes-that-fail-silently) and fix them. The console does not point to them.
4. Fix the errors the console reports, such as `VALID is not defined` or `$(...).scope is not a function`.
5. Port the forms, then test every form by hand: empty, invalid, valid and after a reset.
6. Test the screens that load data, because AJAX callbacks receive fewer arguments.
## Changes that fail silently
Each of these runs without an error in 20.015 and does the wrong thing. Search your code for the left column.
| jComponent 19 | jComponent 20 |
| --- | --- |
| `WATCH('user.name', function(path, value, type) {` | `WATCH('user.name', function(value, flags, path) {` |
| `WATCH('user.*', function(path) {` | `WATCH('user', function(value, flags, path) {` |
| `RESET('form.*');` | `RESET('form');` |
| `GET('form @modified')` | `COMPONENTS('form @modified')` |
| `return value; // a non-empty string means valid` | `return !!value;` |
| `self.setter = function(value, path, type) {` | `self.setter = function(value, path, flags) {` |
| `SET('user.name', 'Ann', 100);` | `setTimeout(() => SET('user.name', 'Ann'), 100);` |
| `SET('form.city', 'Vienna', true);` | `SET('form.city @reset', 'Vienna');` |
| `PUSH('cart.items', [2, 3]);` | `[2, 3].forEach(item => PUSH('cart.items', item));` |
| `SETTER('box', 'show', 1);` | `SETTER('box/show', 1);` |
| `FIND('box', function(com) {` | `WAIT(() => FIND('box'), function() {` |
| `
` | ` ` |
| `` | `` |
| `config="text;format:2"` | `config="text:value.format(2)"` |
| `AJAX('GET /orders/', function(response, err) {` | `ON('response', opt => status = opt.status);` |
A `PLUGIN()` declaration without a `` element also stops running. See [Scopes and plugins](#scopes-and-plugins).
## Forms and validation
`VALID()`, `CAN()`, `DISABLED()`, `INVALID()`, `CHANGE()`, `MODIFIED()` and `DEFAULT()` were removed. Read the state of a form with `COMPONENTS()` and `ERRORS()`, and change it with flags. [Forms and validation](../forms/) describes the new way of working.
| jComponent 19 | jComponent 20 |
| --- | --- |
| `VALID('form.*')` | `COMPONENTS('form @invalid').length === 0` |
| `CAN('form.*')` | `can('form')` (the function below) |
| `DISABLED('form.*')` | `!can('form')` |
| `ERRORS('form.*')` | `ERRORS('form @touched', list => console.log(list.length))` |
| `CHANGE('form.*');` | `UPD('form @change');` |
| `CHANGE('form.*', false);` | `RESET('form');` |
| `MODIFIED('form.*')` | `COMPONENTS('form @modified').map(com => com.path.toString())` |
| `DEFAULT('filter.*');` | `SET('filter @default', {});` |
| `INVALID('form.name');` | `COMPONENTS('form.name').forEach(com => com.reconfigure({ touched: 1, invalid: true }));` |
| `RESET('form.*');` | `RESET('form');` |
`CAN()` has no direct replacement, so keep a small function in your application:
```js
function can(path) {
return COMPONENTS(path + ' @invalid').length === 0 && COMPONENTS(path + ' @touched').length > 0;
}
```
**`ERRORS()` takes a callback.** Without one it throws `r is not a function`. In 19 it returned the fields that were touched and invalid. In 20 it passes every invalid field, so add the `@touched` flag to keep the old result:
```js
ERRORS('form @touched', list => console.log(list.length)); // 0
SET('form.name @change', '');
ERRORS('form @touched', list => console.log(list.map(com => com.path.toString()))); // ["form.name"]
```
**Paths no longer take `.*`.** It does not match anything, and no error is shown. `ERRORS()` then reports a broken form as valid:
```js
ERRORS('form.*', list => console.log(list.length)); // 0
ERRORS('form', list => console.log(list.length)); // 1
```
**`GET('form @modified')` returns the whole model** in 20. Collect the changed fields yourself:
```js
SET('form.city @change', 'Prague');
var changed = {};
COMPONENTS('form @modified').forEach(com => changed[com.path.toString().split('.').pop()] = com.get());
console.log(changed); // {"city":"Prague"}
```
**The result of `self.validate` is read differently.** Any truthy value was valid in 19. In 20 a non-empty string is an error message, so a validator that returns the value marks a filled field as invalid. A number such as `value.length` is invalid too. Return a boolean:
```js
self.validate = function(value) {
return !!value;
};
```
```js
self.validate = function(value) {
return value.length > 0;
};
```
`self.validate` also lost its second argument, `init`. Keep your own flag when the first run needs different treatment:
```js
COMPONENT('field', function(self, config) {
var init = true;
self.validate = function(value) {
console.log(init);
init = false;
return true;
};
});
```
### Binding an input
The `data-jc-bind` attribute is ignored, so the input does not write to the model. Call `self.autobind20()` once the HTML exists:
```js
COMPONENT('textbox', function(self) {
self.make = function() {
self.html(' ');
self.autobind20();
};
});
```
The global `FORMATTER()` and `PARSER()` were removed. Register them on the component:
```js
self.formatter(function(path, value) {
return value ? value.toUpperCase() : value;
});
```
```js
self.parser(function(path, value) {
return value ? value.toLowerCase() : value;
});
```
## Watchers and paths
The arguments of a watcher changed order, and the code keeps running with the wrong values. [Paths](../paths/) describes watchers in 20.
| jComponent 19 | jComponent 20 |
| --- | --- |
| `WATCH('user.name', function(path, value, type) {` | `WATCH('user.name', function(value, flags, path) {` |
| `self.watch('user.name', function(path, value, type) {` | `self.watch('user.name', function(value, flags, path) {` |
| `exports.watch('count', function(value, path, type) {` | `exports.watch('count', function(value, flags, path) {` |
| `WATCH('user.*', function(path) {` | `WATCH('user', function(value, flags, path) {` |
| `WATCHONCE('user.name', function(path, value) {` | `UNWATCH('user.name', once);` inside the callback |
| `ON('watch', 'user.name', function(path, value) {` | `WATCH('user.name', function(value) {` |
A watcher on a parent path also runs for the paths under it, so `WATCH('user', ...)` replaces the wildcard.
## Writing to the model
The third argument of `SET()` was removed. A delay or a reset flag passed there is ignored, and the value is written at once.
| jComponent 19 | jComponent 20 |
| --- | --- |
| `SET('user.name', 'Ann', 100);` | `setTimeout(() => SET('user.name', 'Ann'), 100);` |
| `SET('form.city', 'Vienna', true);` | `SET('form.city @reset', 'Vienna');` |
| `PUSH('cart.items', [2, 3]);` | `[2, 3].forEach(item => PUSH('cart.items', item));` |
| `PUSH('cart.items', 'tea');` on a missing path | `SET('cart.items', ['tea']);` |
| `NOTIFY('user.name');` | `UPD('user.name');` |
| `EXT('user', { age: 30 });` | `SET('user', Object.assign(GET('user'), { age: 30 }));` |
| `MAKE(function(obj) {` | A plain object |
| `EVALUATE('user.age', 'value >= 18')` | `FN('value => value >= 18')(GET('user.age'))` |
| `REMOVECACHE('token');` | `CACHE('token', null, '1 day');` |
| `CL_INIT('colors', function(next) {` | `CLINIT('colors', function(next) {` |
`PUSH()` to a path that does not exist notifies no watcher, so create the array with `SET()`.
The third argument of `CACHEPATH()` is now a default value, and the values saved by jComponent 19 are not read:
```js
CACHEPATH('filter.q', '1 day', 'all');
console.log(GET('filter.q')); // all
```
## Calling components and functions
| jComponent 19 | jComponent 20 |
| --- | --- |
| `SETTER('box', 'show', 1);` | `SETTER('box/show', 1);` |
| `RECONFIGURE('box', 'size:2');` | `SETTER('box/reconfigure', 'size:2');` |
| `RETURN('box/name')` | `FIND('box').name` |
| `FIND('box', function(com) {` | `WAIT(() => FIND('box'), function() {` |
| `EXEC(true, 'FUNC.start', 'now');` | `EXEC('FUNC.start @important', 'now');` |
| `AEXEC('FUNC.save', 1)` | `() => EXEC('FUNC.save', 1)` |
| `ADD('box__user.name', '#panel');` | `$('#panel').append(' ');` |
## Markup attributes
The attribute forms are ignored without an error, and the elements stay empty. Use the custom elements described in [Using components](../using-components/) and [Data binding](../data-binding/).
| jComponent 19 | jComponent 20 |
| --- | --- |
| `
` | ` ` |
| ` ` | ` ` |
| `` | `
` |
## Scopes and plugins
There is no scope object in 20. A `` element is the scope, and `$(selector).plugin()` returns the instance. An element with `?` paths outside a `` is not rendered. [Plugins](../plugins/) describes the plugin object.
| jComponent 19 | jComponent 20 |
| --- | --- |
| `var scope = $('#panel').scope();` | `var plugin = $('#panel').plugin();` |
| `console.log(scope.path); // invoice` | `console.log(plugin.path.toString()); // invoice` |
| `scope.watch('number', function(path, value) {` | `plugin.watch('number', function(value, flags, path) {` |
| `` nested in a plugin | `` |
| `` | `` |
| `` | `exports.set('user', 'guest');` in the plugin |
| `function loginready(path, element) {` | `function loginready(element) {` |
| `config="text:?/format"` | `config="text:PLUGINS.contact.format(value)"` |
A nested `` no longer extends the path of its parent. Write `?` in the path to get the old result, otherwise the plugin reads a global path of the same name:
```html
```
**A plugin needs its element.** In 19 `PLUGIN()` created the instance on its own. In 20 the callback runs only when a `` element with that path exists, so a plugin without one never starts:
```html
```
| jComponent 19 | jComponent 20 |
| --- | --- |
| `exports.extend('filter', { page: 2 });` | `exports.set('filter', Object.assign(exports.get('filter'), { page: 2 }));` |
| `PLUGINS.orders.reset();` | `RESET(PLUGINS.orders.path.toString());` |
| `exports.api('/api/ orders_list', { page: 1 }, function() {` | `API('/api/', 'orders_list', { page: 1 }, function() {` |
| `console.log(exports.modified); // {"city":"Prague"}` | The code below |
`exports.modified` returns the whole model and clears the state of the components. Collect the changed fields first:
```js
var changed = {};
COMPONENTS(exports.path + ' @modified').forEach(com => changed[com.path.toString().split('.').pop()] = com.get());
RESET(exports.path.toString());
console.log(changed); // {"city":"Prague"}
```
## ui-bind commands
Several commands of `` were removed, and most of them are skipped without an error. The expression of a command is plain JavaScript, so a call inside it replaces most of them. The [ui-bind reference](../../reference/ui-bind/) lists the commands of 20.
| jComponent 19 | jComponent 20 |
| --- | --- |
| `config="text;format:2"` | `config="text:value.format(2)"` |
| `config="text;currency:eur"` | `config="text:value.currency('eur')"` |
| `config="text;default:'none'"` | `config="text:value == null ? 'none' : value"` |
| `config="text;helper:pluralize('no items','# item','# items','# items')"` | `config="text:value.pluralize('no items','# item','# items','# items')"` |
| `config="text;selector:b"` | `config="text" child="b"` |
| `config="checked input"` | `config="checked"` |
| `config="init:FUNC.start;text"` | `config="exec:FUNC.start;text"` |
| `config="click:FUNC.open"` | `Open ` |
| `config="setter:'box/show',value"` | `config="exec:FUNC.show"` |
| `config="config:'size:' + value"` | ` ` |
**The value `false` renders as empty** with the `text` command. Convert the value to a string:
```html
```
## Components
The `path` of a component is now an object. Comparing it with a string gives `false`, and string methods such as `split()` do not exist on it, so convert it first. The third argument of `self.setter` is an object with flags in place of a number. [Creating components](../creating-components/) describes the delegates.
| jComponent 19 | jComponent 20 |
| --- | --- |
| `self.path === 'form.name'` | `self.path.toString() === 'form.name'` |
| `self.setter = function(value, path, type) {` | `self.setter = function(value, path, flags) {` |
| `type === 0` | `flags.init` |
| `self.notify();` | `self.upd();` |
| `self.faicon('home')` | `self.icon('home')` |
| `self.scopepath('user.age')` | `self.makepath('user.age')` |
| `self.inc(2);` | `self.set(self.get() + 2);` |
| `self.extend({ b: 2 });` | `self.set(Object.assign(self.get(), { b: 2 }));` |
| `self.dirty()` | `!config.touched` |
| `self.dirty(false);` | `self.touch();` |
| `self.invalid();` | `self.reconfigure({ touched: 1, invalid: true });` |
| `self.skip();` before `self.set(2);` | `self.rewrite(2);` |
| `self.main()` | `self.element.parent().component()` |
| `self.exec('show', 1)` | `self.element.SETTER('*/show', 1)` |
| `self.data('page', 2);` | A variable inside the component |
The arguments of `self.state(type, what)` have different values in 20. Read the state from `config`:
```js
self.state = function() {
if (config.touched && config.modified && !changed) {
changed = true;
console.log('changed');
}
};
```
`self.bindchanges()` was removed. Compare the value in the setter:
```js
var last;
self.setter = function(value) {
if (value !== last) {
last = value;
console.log(value);
}
};
```
## Macros and virtual bindings
`MACRO()`, the `macro` command, `VBIND()`, `VBINDARRAY()` and the `vbindarray` command were removed. Rewrite a macro as a component, and rewrite a virtual binding as a `template` command with [Tangular](../tangular/).
| jComponent 19 | jComponent 20 |
| --- | --- |
| `MACRO('clicks', function(self, element) {` | `COMPONENT('clicks', function(self) {` |
| `config="macro:clicks"` | ` ` |
| `VBIND('
')` | `config="template"` |
| `VBINDARRAY(' ', '#list')` | `config="template"` |
| `config="vbindarray"` | `config="template"` |
```html
```
```js
COMPONENT('clicks', function(self) {
self.make = function() {
self.event('click', () => self.set((self.get() || 0) + 1));
};
self.setter = function(value) {
self.text('Clicked ' + (value || 0));
};
});
```
A list that used `VBINDARRAY()` becomes a template:
```html
```
## The M object
`M` still exists and is the same object as `jComponent` and `MAIN`. `M.version`, `M.components` and `M.binders` work as before. The methods that changed the model were removed or take different arguments, so use the global functions.
| jComponent 19 | jComponent 20 |
| --- | --- |
| `M.set('user.name', 'Ann');` | `SET('user.name', 'Ann');` |
| `M.inc('user.age', 2);` | `INC('user.age', 2);` |
| `M.push('user.tags', 'new');` | `PUSH('user.tags', 'new');` |
## AJAX and APIs
The callback of `AJAX()` receives only the response, and `AJAX()` no longer returns a Promise. The [Global functions](../../reference/globals/) reference describes `AJAX()`.
| jComponent 19 | jComponent 20 |
| --- | --- |
| `AJAX('GET /orders/', function(response, err) {` | `ON('response', opt => status = opt.status);` |
| `AJAX('GET /orders/').then(function(response) {` | `new Promise(resolve => AJAX('GET /orders/', resolve)).then(function(response) {` |
| `AJAX('GET /orders/ error', () => console.log('callback'));` | `AJAX('GET /orders/ ERROR', () => console.log('callback'));` |
| `AJAX('GET /orders/ {"X-Token":"abc"}', function() {` | `ON('request', opt => opt.headers['X-Token'] = 'abc');` |
| `AJAXCONFIG('secure', function(options) {` | `ON('request', function(options) {` |
| `AJAXCACHE('GET /orders/', null, NOOP, '1 minute');` | `AJAX('GET /orders/ <1 minute>', NOOP);` |
| `AJAX('GET /orders/', null, 'orders', 100);` | `setTimeout(() => AJAX('GET /orders/', 'orders'), 100);` |
| `API('/api/ users_save', { name: 'Ann' }, function() {` | `API('/api/', 'users_save', { name: 'Ann' }, function() {` |
| `DAPI('users_save', { name: 'Ann' }, function() {` | `TAPI('users_save', { name: 'Ann' }, function() {` |
To read the status code of a response, listen to the `response` event ahead of the request:
```js
var status = 0;
ON('response', opt => status = opt.status);
AJAX('GET /orders/', function(response) {
console.log(response.error, status); // denied 403
});
```
## Settings
| jComponent 19 | jComponent 20 |
| --- | --- |
| `DEF.validators.email` | `DEF.regexp.email` |
| `DEF.pathcommon` | `DEF.path.common` |
| `DEF.pathcl` | `DEF.path.cl` |
| `DEF.environment` | `DEF.env` |
| `DEF.languagehtml = 'sk';` | `DEF.language = 'sk';` |
These settings no longer exist: `ajaxcredentials`, `ajaxcredentialshtml`, `ajaxerrors`, `customelements`, `delay`, `delaybinder`, `delaykeypress`, `delaypref`, `delayrepeat`, `delaywatcher`, `fallbackcache`, `importcache`, `jsoncompress`, `jsonconverter`, `jsondate`, `keypress`, `makeurl`, `monitor`, `prefixcssmacros`, `repeatfocus`, `scope`, `secret` and `versioncomponents`. The [DEF](../../reference/def/) reference lists the settings of 20.
## Events
| jComponent 19 | jComponent 20 |
| --- | --- |
| `ON('destroy', name => console.log('removed', name));` | `self.destroy = () => console.log('removed', self.name);` |
| `ON('watch', 'user.name', function(path, value) {` | `WATCH('user.name', function(value) {` |
The `exec` event is no longer emitted. `WW` and `WH` are not set until the library starts, so read them inside `ON('ready', ...)`. The [Events](../../reference/events/) reference lists the events of 20.
## jQuery helpers
| jComponent 19 | jComponent 20 |
| --- | --- |
| `$('#panel').components()` | `$('#panel').COMPONENTS()` |
| `$('#panel').FIND('box')` | `$('#panel').COMPONENTS().findItem('name', 'box')` |
| `$('#panel').RECONFIGURE('box', 'size:2');` | `$('#panel').SETTER('box/reconfigure', 'size:2');` |
| `$('#panel').EMIT('hello', 1);` | `EMIT('hello', 1);` |
## String, number, date and array helpers
| jComponent 19 | jComponent 20 |
| --- | --- |
| `'Hello {name}'.arg({ name: 'Ann' })` | `'Hello {name}'.args({ name: 'Ann' })` |
| `'{{ name }}'.render({ name: 'Ann' })` | `Tangular.render('{{ name }}', { name: 'Ann' })` |
| `'Ann '.removeTags()` | `'Ann '.replace(/<[^>]*>/g, '')` |
| `'a=1&b=2'.parseEncoded()` | `Object.fromEntries(new URLSearchParams('a=1&b=2'))` |
| `new Date(2026, 0, 5).toNumber()` | `+new Date(2026, 0, 5).format('yyyyMMdd')` |
| `new Date(2026, 0, 5).parseDate()` | `new Date(2026, 0, 5)` |
| `(5).between({ 1: 'low', 10: 'high' })` | `value < 10 ? 'low' : 'high'` |
| `tasks.async(() => console.log('done'));` | `tasks.wait((task, next) => task(next), () => console.log('done'));` |
`String.parseConfig()` no longer accepts a callback, and it ignores one without an error. Loop over the returned object:
```js
var config = 'size:2;open:true'.parseConfig();
for (var key in config)
console.log(key, config[key]);
```
## Functions without a replacement
These global functions were removed, and 20.015 has no direct equivalent.
| jComponent 19 | jComponent 20 |
| --- | --- |
| `WAPI`, `WAPI_INIT`, `AJAXCACHEREVIEW` | No replacement |
| `DEBUG`, `STOPDEBUG` | No replacement |
| `QUEUE`, `REPEAT`, `WORKFLOW` | No replacement |
| `PLUGINABLE`, `VERSION`, `IMPORTCACHE` | No replacement |
| `CLEARCACHE`, `REWRITE`, `REWRITE2`, `NOTMODIFIED`, `BIND`, `OPT` | No replacement |
## A complete form
This form has two required fields and a button that is enabled once the form is valid. Both versions behave the same: the first save reports the two invalid paths, and a save with filled fields returns the model.
Before, in jComponent 19:
```html
Save
```
After, in jComponent 20:
```html
Save
```
---
title: Paths
project: jComponent V20
version: 20.015
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/guides/paths/
updated: 2026-11-18T13:55:34.124Z
---
# Paths
> How to address, read, change and watch values of the model with string paths.
A path is a string that addresses a value in the global `window` object: `app.user.name` is the same value as `window.app.user.name`. All data in jComponent is read and written through paths, which is how the library knows what has changed and who needs to be told.
## Reading and writing values
`SET(path, value)` writes a value and notifies everything that depends on the path. `GET(path)` reads a value.
```js
SET('app.user.name', 'Ana');
console.log(app.user.name);
console.log(GET('app.user.name'));
console.log(GET('app.user'));
console.log(GET('app.company.name'));
```
```text
Ana
Ana
{"name":"Ana"}
undefined
```
`SET()` creates the missing objects along the path. `GET()` returns `undefined` when a part of the path does not exist.
The first part of a path is a global variable, so choose a name that the browser does not already use. Names such as `name`, `location` or `status` belong to `window`.
## Path syntax
| Path | Meaning |
| --- | --- |
| `app.user.name` | A nested key |
| `shop.products[1].name` | A key of an existing array item |
| `shop.tags[]` | With `SET()`, appends the value to an array and creates the array when it is missing |
| `shop.prices['pen.blue']` | A key that contains a dot |
```js
SET('shop.products', [{ name: 'Pen' }, { name: 'Book' }]);
SET('shop.products[1].name', 'Notebook');
console.log(GET('shop.products[1].name'));
SET('shop.tags[]', 'new');
SET('shop.tags[]', 'sale');
console.log(GET('shop.tags'));
SET("shop.prices['pen.blue']", 12);
console.log(GET("shop.prices['pen.blue']"));
```
```text
Notebook
["new","sale"]
12
```
## Changing values
| Function | What it does |
| --- | --- |
| `SET(path, value)` | Writes a value |
| `INC(path, [value])` | Adds a number to the value, `1` by default |
| `TOGGLE(path)` | Negates the value |
| `PUSH(path, value)` | Appends a value to an existing array. With the prefix `^`, the value goes to the start of the array |
| `NUL(path)` | Writes `null` |
```js
SET('cart.count', 1);
INC('cart.count');
INC('cart.count', 5);
console.log(cart.count);
TOGGLE('cart.open');
console.log(cart.open);
SET('cart.items', ['b']);
PUSH('cart.items', 'c');
PUSH('^cart.items', 'a');
console.log(cart.items);
NUL('cart.count');
console.log(cart.count);
```
```text
7
true
["a","b","c"]
null
```
## Who is notified
A change reaches listeners on the same path, on its parent paths and on its child paths. Listeners on sibling paths are left alone.
```js
WATCH('order', () => console.log('order'));
WATCH('order.customer', () => console.log('order.customer'));
WATCH('order.customer.name', () => console.log('order.customer.name'));
WATCH('order.total', () => console.log('order.total'));
SET('order.customer', { name: 'Ana' });
```
```text
order
order.customer
order.customer.name
```
The watcher of `order.total` does not run, because `order.customer` is neither its parent nor its child.
## Changing the model directly
The model is a plain object, so you can change it with normal JavaScript. The library does not see such a change. Call `UPD(path)` to announce it:
```js
SET('todo.items', ['Write']);
WATCH('todo.items', function(value, flags, path) {
console.log(path, value.length);
});
// Changing the object directly notifies nobody
todo.items.push('Test');
// UPD() tells everybody that the value has changed
UPD('todo.items');
```
```text
todo.items 2
```
## Watching a path
`WATCH(path, callback, [init])` runs a function whenever the value at the path changes. `UNWATCH(path, [callback])` removes the watcher. Without the `callback` argument, it removes all watchers of the path.
The callback receives three arguments:
| Argument | Description |
| --- | --- |
| `value` | The current value at the watched path |
| `flags` | An object with the [flags](../flags/) of the operation |
| `path` | The path that was changed, which can be a parent or a child of the watched path |
```js
function onchange(value, flags, path) {
console.log(path, value);
}
WATCH('stats.visits', onchange);
SET('stats.visits', 1);
UNWATCH('stats.visits', onchange);
SET('stats.visits', 2);
// Several paths with one callback
WATCH('stats.a + stats.b', onchange);
SET('stats.a', 10);
SET('stats.b', 20);
// The third argument calls the callback right after the registration
SET('stats.c', 30);
WATCH('stats.c', onchange, true);
```
```text
stats.visits 1
stats.a 10
stats.b 20
stats.c 30
```
To display a value on the page, you do not need a watcher. Use [data binding](../data-binding/).
## Shortcuts
Paths support prefixes for common places in the model, such as `*title` for `common.title`. They are described in [Flags and path modifiers](../flags/).
---
title: Flags and path modifiers
project: jComponent V20
version: 20.015
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/guides/flags/
updated: 2026-11-18T13:55:34.124Z
---
# Flags and path modifiers
> How flags change the behaviour of an operation on a path and how path modifiers shorten paths.
A flag is a word that starts with `@` and follows a path, separated by a space: `SET('form.name @change', 'Ana')`. Flags tell the library, the components and your own code how to treat the operation. A path modifier is a character that changes what the path points to, such as `*` in `*title`.
## Passing flags
Add any number of flags after the path. Watchers and component setters receive them as an object. A flag can carry a value in the form `@name:value`.
```js
WATCH('form.name', function(value, flags) {
console.log(value, flags);
});
SET('form.name @mine', 'Ana');
SET('form.name @mode:edit @type:3', 'Peter');
```
```text
Ana {"mine":1}
Peter {"mode":"edit","type":3}
```
The value of the flag `@type` is converted to a number when it starts with a digit. Values of other flags stay strings.
## Flags for the state of components
Each component tracks whether the user has touched and modified it. These flags change that state for all components on the path:
| Flag | Effect |
| --- | --- |
| `@change`, `@touch`, `@modify`, `@modified` | Marks the components as touched and modified |
| `@reset` | Clears the touched and modified state |
| `@default` | Clears the state and fills empty values from the `default` attribute of the component |
```html
```
```js
ON('ready', function() {
var el = document.getElementById('name');
SET('form.name @change', 'Ana');
console.log(el.className);
SET('form.name @reset', 'Peter');
console.log('[' + el.className + ']');
SET('form.name @touch', 'Eva');
console.log(el.className);
GET('form.name @reset');
console.log('[' + el.className + ']');
});
```
```text
ui-touched ui-modified
[]
ui-touched ui-modified
[]
```
The state is visible in the CSS classes `ui-touched` and `ui-modified`. `GET()` with a flag notifies the path and returns the value, so `GET('form.name @reset')` resets the state without changing the data. `RESET(path)` does the same for a whole path.
The flag `@default` uses the value of the `default` attribute when the model contains `null` or `undefined`:
```html
```
```js
ON('ready', function() {
SET('form.age', 30);
console.log(form.age);
SET('form.age @default', null);
console.log(form.age);
});
```
```text
30
18
```
## Filtering components
`COMPONENTS(path)` returns the components on a path. Flags limit the result:
| Flag | Returns the components that are |
| --- | --- |
| `@touched` | touched |
| `@modified` | modified |
| `@required` | configured with `required:true` |
| `@invalid` | invalid |
| `@valid` | valid |
| `@disabled` | disabled |
| `@enabled` | not disabled |
| `@visible` | visible on the page |
| `@hidden` | hidden on the page |
```html
```
```js
COMPONENT('field', function(self, config) {
self.validate = function(value) {
return !config.required || !!value;
};
});
ON('ready', function() {
SET('form.name @change', 'Ana');
const names = list => list.map(com => com.path.toString());
console.log(names(COMPONENTS('form')));
console.log(names(COMPONENTS('form @required')));
console.log(names(COMPONENTS('form @invalid')));
console.log(names(COMPONENTS('form @modified')));
console.log(names(COMPONENTS('form @disabled')));
});
```
```text
["form.name","form.email","form.note"]
["form.name","form.email"]
["form.email"]
["form.name"]
["form.note"]
```
[Forms and validation](../forms/) shows how to use the state in a form.
## Waiting for a target
`EXEC()` and `SETTER()` do nothing when the function or the component does not exist yet. With the flag `@important`, they try again every 500 milliseconds until the target appears.
```js
EXEC('FUNC.start @important', 'now');
setTimeout(function() {
FUNC.start = function(value) {
console.log('started', value);
};
}, 100);
```
```text
started now
```
## Custom flags
A custom flag emits the event `@flag name`, and the handler receives the path. `UPD()`, `EMIT()` and `FLAGS(flags, [callback])` accept custom flags:
```js
ON('@flag saved', function(path) {
console.log('saved:', path);
});
SET('invoice.total', 100);
UPD('invoice.total @saved');
FLAGS('@saved @other', function() {
console.log('flags processed');
});
EMIT('finished @saved');
```
```text
saved: invoice.total
saved:
flags processed
saved:
```
## Path modifiers
| Modifier | Example | Points to |
| --- | --- | --- |
| `*` | `*title` | `common.title` |
| `%` | `%search` | `DEF.tmp.search`, a place for temporary values |
| `#` | `#languages` | `DEF.cl.languages`, a code list |
| `[key]` | `[section].count` | The part in brackets is replaced by the environment value set with `ENV()` |
| ` #name` | `user.language #languages` | With `SET()`, the value is written after the code list `languages` has loaded |
```html
```
```js
SET('*title', 'Common title');
console.log(common.title);
SET('%search', 'pen');
console.log(DEF.tmp.search);
ENV('section', 'invoices');
SET('[section].count', 5);
console.log(invoices.count);
CLINIT('languages', function(next) {
next([{ id: 'en' }, { id: 'sk' }]);
});
SET('user.language #languages', 'sk');
ON('ready', function() {
CL('languages', function() {
console.log(user.language, GET('#languages').length);
});
});
```
```text
Common title
pen
5
sk 2
```
`CLINIT(name, callback)` declares how a code list loads, and `CL(name, callback)` runs a function when it is available.
### Paths in plugins
| Modifier | Example | Points to |
| --- | --- | --- |
| `?` | `?.name` | The model of the closest parent plugin |
| `?\|` | `?\|title` | A property of the closest parent plugin instance |
| `\|` | `contact\|title` | A property of the plugin registered as `contact` |
```html
```
```js
PLUGIN('contact', function(exports) {
exports.title = 'Contact form';
exports.make = function() {
exports.set('name', 'Ana');
};
});
```
The first `` shows `Ana` and the second shows `Contact form`. Read more in [Plugins](../plugins/).
### Prefixes of functions and elements
| Prefix | Used in | Effect |
| --- | --- | --- |
| `^` | `PUSH('^list', value)` | Inserts the value at the start of the array |
| `!` | `` | Skips rendering while the value is `null` or `undefined` |
| `!` | `SETTER('!dialog/open')` | Does not create a [lazy component](../using-components/) |
---
title: Data binding
project: jComponent V20
version: 20.015
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/guides/data-binding/
updated: 2026-11-18T13:55:34.124Z
---
# Data binding
> How to render values of the model into the page with ui-bind and keep inputs and the model in sync.
Data binding connects the model to the page. The `` element renders a value from a path and renders it again whenever the value changes. Components add the opposite direction: they write what the user enters back to the model.
## The ui-bind element
`` has two main attributes. `path` is the value to listen to and `config` is a list of commands separated by semicolons. A command in the form `name:expression` uses the result of a JavaScript expression. Without an expression, the command uses the value itself.
```html
```
```js
SET('user', { name: 'Ana', age: 30 });
```
The three elements show `Ana`, `ANA` and `adult`.
An expression can use these variables:
| Variable | Description |
| --- | --- |
| `value` | The value at the path |
| `element`, `el` | The target element as a jQuery object |
| `flags` | The [flags](../flags/) of the operation |
| `path` | The path that was changed |
Inside `config`, write a semicolon as `\;`:
```html
```
## Commands
| Command | Effect |
| --- | --- |
| `text` | Sets the text content |
| `html` | Sets the HTML content |
| `value` | Sets the value of a form control |
| `title`, `href`, `src` | Sets the attribute of the same name |
| `attr name` | Sets the attribute `name` |
| `.name` | Adds the CSS class `name` when the result is truthy and removes it otherwise |
| `show` | Adds the class `hidden` when the result is falsy |
| `hide` | Adds the class `hidden` when the result is truthy |
| `visible` | Adds the class `invisible` when the result is falsy |
| `invisible` | Adds the class `invisible` when the result is truthy |
| `disabled` | Disables the form controls inside the target when the result is truthy |
| `enabled` | Disables the form controls inside the target when the result is falsy |
| `checked` | Checks the inputs inside the target when the result is truthy |
| `template` | Renders a [Tangular](../tangular/) template |
| `exec` | Calls a function with the arguments `value`, `path` and `element` |
While `show`, `hide`, `visible` or `invisible` keeps the element hidden, `text`, `html` and `template` do not render. They render when the element is displayed again.
The [ui-bind reference](../../reference/ui-bind/) describes all commands and options.
## Choosing the target
By default, a command changes the `` element itself. Write a CSS selector after the command to change elements inside it:
```html
Detail
```
```js
SET('product', { id: 7, name: 'Pen', price: 12, url: '/products/pen/', discount: 10 });
```
The rendered result:
```html
Pen
12 EUR
Detail
```
Form controls and visibility work the same way:
```html
Shown when the value is truthy
Hidden when the value is truthy
Save
```
```js
SET('panel', { open: true, locked: true, accepted: true, note: 'Hello' });
```
Three attributes move the target of all commands outside the default element:
| Attribute | Target |
| --- | --- |
| `element` | Any element on the page that matches the selector |
| `parent` | The closest parent that matches the selector |
| `child` | The elements inside `` that match the selector |
```html
untouched
```
```js
SET('page', { title: 'Invoices', active: true });
```
## Rendering lists
The `template` command compiles the content of a `
```
```js
SET('team.members', [{ name: 'Ana' }, { name: 'Peter' }]);
```
Each change of `team.members` renders the list again. For the template syntax, read [Templates with Tangular](../tangular/).
## Controlling when it renders
| Option | Effect |
| --- | --- |
| `!` in front of the path | Skips rendering while the value is `null` or `undefined` |
| `strict` | Renders only when the exact path changes, not its children |
| `track:a,b` | For changes of child paths, renders only for the listed keys |
| `changes` | Renders only when the value is different from the last rendered one |
| `delay:100` | Waits for the given number of milliseconds and renders the last value |
| `once` | Renders once and stops listening |
| `check:FUNC.name` | Renders only when the function returns a truthy value. Arguments: `value`, `path`, `element` |
| `empty:text` | Shows this text for an empty value. Without a text, it shows `---` |
```html
```
```js
FUNC.positive = value => value > 0;
FUNC.rendered = value => console.log('rendered', value);
SET('report.data', { a: 1, b: 1 });
SET('report.version', 1);
```
After these changes:
```js
SET('report.total', 5);
SET('report.data.a', 2);
SET('report.data.b', 2);
SET('report.version', 2);
```
| Element | Shows | Why |
| --- | --- | --- |
| `#a` | `Total: 5` | It stayed empty until the value appeared |
| `#b` | `1` | `strict` ignores changes of `report.data.a` and `report.data.b` |
| `#c` | `1` | It renders `value.b` but tracks only the key `a` |
| `#d` | `2` | The value has changed |
| `#f` | `1` | `once` rendered only the first value |
| `#g` | `5` | The check passed. For `-1`, the element would keep showing `5` |
## Two-way binding
`` only displays data. To let the user change a value, use a component on the same path. A component receives changes of the model and writes the user's input back:
```html
You live in
```
```js
COMPONENT('textbox', function(self) {
self.make = function() {
self.html(' ');
self.autobind20();
};
});
SET('profile.city', 'Bratislava');
```
The input starts with `Bratislava`. When the user types `Kosice`, the model and the paragraph change. A later `SET('profile.city', 'Nitra')` updates both the input and the paragraph. [Creating components](../creating-components/) explains `autobind20()`.
## Reacting in code
To run code when a value changes, use `WATCH()` as described in [Paths](../paths/), or the `exec` command:
```js
FUNC.log = function(value, path, element) {
console.log(value, path.toString(), element.prop('tagName'));
};
SET('note.text', 'Hi');
```
```text
Hi note.text UI-BIND
```
---
title: Using components
project: jComponent V20
version: 20.015
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/guides/using-components/
updated: 2026-11-18T13:55:34.124Z
---
# Using components
> How to place components on a page, configure them, find them and call their methods.
A component is a reusable widget declared once and placed on the page with the `` element. This guide covers how to use existing components. To write your own, read [Creating components](../creating-components/).
## Adding a component
```html
```
| Attribute | Description |
| --- | --- |
| `name` | The name of the component |
| `path` | The path of the value that the component works with. Components without a value do not need it |
| `config` | The configuration of this instance |
| `default` | A JavaScript expression that fills the model when the value is `null` or `undefined` at startup |
| `source` | The 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 `` 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.
```html
```
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:
```js
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.
```html
```
```js
COMPONENT('box', 'limit:5;color:red', function(self, config) {
self.make = function() {
console.log(config);
};
});
```
```text
{"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:
| Key | Description |
| --- | --- |
| `$id` | Sets the identifier of the instance |
| `$class` | Adds CSS classes to the element |
| `$assign` | Stores the instance at a path |
| `$init` | Calls a function when the component is initialized. The argument is the instance |
| `$setter` | Calls a function each time the value changes. Arguments: `value`, `path`, `flags` |
| `=key` | Reads the value of the configuration key `key` from a path and follows its changes |
```html
```
```js
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'));
});
```
```text
ready mainbox
value undefined
value Ana
box highlighted
```
A configuration key linked to a path changes together with the model:
```html
```
```js
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.
```html
```
```js
CONFIG('box', 'size:large');
ON('ready', function() {
CONFIG('box', { color: 'green' });
console.log(FIND('box', true).map(com => com.config.color));
});
```
```text
new red large
new blue large
["green","green"]
```
## Finding components
| Code | Returns |
| --- | --- |
| `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](../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.
```html
```
```js
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);
});
```
```text
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:
```js
SETTER('notify/show @important', 'Saved');
setTimeout(function() {
COMPONENT('notify', function(self) {
self.show = message => console.log(message);
});
$(document.body).append(' ');
}, 100);
```
```text
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.
```html
```
```js
COMPONENT('dialog', function(self) {
self.make = () => console.log('created');
self.open = title => console.log('open', title);
});
ON('ready', function() {
SETTER('dialog/open', 'Settings');
});
```
```text
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 class | Configuration key | Meaning |
| --- | --- | --- |
| `ui-touched` | `touched` | The user has interacted with the component |
| `ui-modified` | `modified` | The user has changed the value |
| `ui-invalid` | `invalid` | The value did not pass the validation of the component |
| `ui-disabled` | `disabled` | The component is disabled |
```html
```
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](../forms/).
## 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.
```js
ON('ready', function() {
$('#area').empty();
FREE();
console.log(FIND('box', true).length);
$('#area').html(' ');
});
```
`FIND('name').remove()` removes one component and its element immediately.
---
title: Creating components
project: jComponent V20
version: 20.015
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/guides/creating-components/
updated: 2026-11-22T18:41:52.302Z
---
# Creating components
> How to declare your own components, handle values and configuration, validate input and clean up.
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](../using-components/).
## Declaring a component
```js
COMPONENT(name, [config], callback, [dependencies], [css]);
```
| Argument | Type | Description |
| --- | --- | --- |
| `name` | String | The name used in `` |
| `config` | String | The default configuration in the form `key:value;key:value` |
| `callback` | Function | Runs for each instance with the arguments `self`, `config` and `cls` |
| `dependencies` | String or Array | Resources to load ahead of the initialization. A string can list several URLs separated by commas |
| `css` | String | The CSS of the component |
```html
```
```js
COMPONENT('hello', 'name:World', function(self, config, cls) {
self.make = function() {
self.aclass(cls);
self.text('Hello ' + config.name);
};
});
```
The rendered element:
```html
Hello Ana
```
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](../using-components/).
## Lifecycle
You define the behaviour of a component by assigning functions, called delegates, to `self`. The library calls them in this order:
```html
```
```js
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);
```
```text
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
```
| Delegate | When 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
| Property | Description |
| --- | --- |
| `self.element` | The element as a jQuery object |
| `self.dom` | The DOM element |
| `self.config` | The configuration |
| `self.path` | The path of the component. Use `self.path.toString()` to get a string |
| `self.name` | The name of the component |
| `self.id` | The identifier of the instance |
The complete list is in the [Component reference](../../reference/component/).
## 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](../flags/) of the operation. The library adds `init` for the first call and `refresh` for `self.refresh()`.
```html
```
```js
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();
});
```
```text
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
| Method | Effect |
| --- | --- |
| `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 |
```html
Quantity:
```
```js
COMPONENT('stepper', 'step:1', function(self, config) {
self.make = function() {
self.html('- + ');
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:
```html
```
```js
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);
});
```
```text
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()`.
```html
```
```js
COMPONENT('input', function(self, config) {
self.make = function() {
self.html(' ');
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:
```text
{"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.
```html
```
```js
COMPONENT('textbox', 'maxlength:10', function(self, config) {
self.make = function() {
self.html(' ');
};
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'));
});
```
```text
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.
```html
```
```js
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);
});
```
```text
1 Enter 4 digits
false
0
```
| Method | Effect |
| --- | --- |
| `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.
```html
Title
```
```js
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:
```css
.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])`.
```html
```
```js
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);
});
```
```text
[]
first handler 2
second handler 2
```
## Events and watchers
| Method | Description |
| --- | --- |
| `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 |
```html
```
```js
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');
});
```
```text
user Ana app.user
own path online
logout timeout
```
## Cleaning up
Release timers and other resources in `self.destroy`:
```html
```
```js
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
| Method | Effect |
| --- | --- |
| `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 |
```html
```
```js
COMPONENT('toast', function(self) {
self.singleton();
self.make = () => console.log('created once');
});
```
The delegate `make` runs once and one `` element stays on the page.
```html
```
```js
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.
```html
```
```js
COMPONENT('map', '', function(self) {
self.make = () => console.log('ready to use', W.mapsdk);
}, [
'https://example.com/maps.js',
function(next) {
W.mapsdk = 'loaded';
next();
}
]);
```
---
title: Plugins
project: jComponent V20
version: 20.015
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/guides/plugins/
updated: 2026-11-18T13:55:34.124Z
---
# Plugins
> How to group the data, the logic and the markup of one part of an application into a plugin.
A plugin holds one part of an application: a page, a form, a dialog. It owns a piece of the data model, keeps the logic that works with it, and gives the markup inside its element short relative paths. A plugin has two parts: a declaration made with `PLUGIN()` and a `` element that creates an instance of it.
## Declaring a plugin
`PLUGIN(name, [config], callback, [dependencies])` registers a declaration. The `path` attribute of `` selects the declaration and sets where the plugin keeps its data.
```html
Add
```
The console prints `counter 2 Clicks`, and two clicks on the button leave `4` in `counter.count`.
The callback receives three arguments:
| Argument | Description |
| --- | --- |
| `exports` | The plugin instance. It is also the value of `this`. |
| `config` | The merged configuration. |
| `cls` | The value of the `path` attribute of the element. |
The instance exposes `name`, `path`, `element`, `dom` and `config`. All its methods are listed in the [Plugin](../../reference/plugin/) reference.
## Working with the plugin data
Inside the markup of a plugin, `?` stands for the plugin path. `?.count` in the plugin `counter` is the global path `counter.count`. Read more about paths in [Paths](../paths/).
In the code, the methods of `exports` take a path relative to the plugin:
```js
PLUGIN('cart', function(exports) {
exports.make = function() {
exports.set('title', 'My cart');
exports.push('items', 'Apple');
exports.push('items', ['Pear', 'Plum']);
exports.inc('count', 3);
exports.toggle('open');
exports.nul('title');
console.log(JSON.stringify(exports.model));
console.log(exports.get('items.length'));
};
});
```
```text
{"title":null,"items":["Apple","Pear","Plum"],"count":3,"open":true}
3
```
`exports.model` reads or replaces the whole plugin data, and `exports.data` is the same value. Every write notifies the components, bindings and watchers on that path. `exports.upd(path)` sends the notification without changing the value.
## Methods
Each function assigned to `exports` is a method that other code can call:
| Where | How to call it |
| --- | --- |
| Any script | `EXEC('inbox/clear')` |
| Markup inside the plugin | `` |
| The plugin itself | `exports.exec('clear')` |
A click on an element with the class `exec` calls the method with the element and the event as arguments. Every instance is also available as `PLUGINS.name`.
## Watching data and listening to events
`exports.watch(path, callback, [autoinit])` reacts to changes under the plugin path. `exports.on(name, callback)` listens to a global event sent with `EMIT()`.
```js
PLUGIN('inbox', function(exports) {
exports.watch('unread', function(value, flags, path) {
console.log('watch', path, value);
});
exports.on('message', function(text) {
exports.inc('unread');
console.log('event', text);
});
exports.clear = function() {
exports.set('unread', 0);
};
});
EMIT('message', 'Hello');
EXEC('inbox/clear');
SET('inbox.unread', 5);
```
```text
watch inbox.unread 1
event Hello
watch inbox.unread 0
watch inbox.unread 5
```
Call `EMIT()` and `EXEC()` once the plugin exists, for example in `ON('ready', callback)`.
## Configuration
The configuration of the element overrides the configuration of the declaration. Three keys have a special meaning:
| Key | Description |
| --- | --- |
| `init` | The name of a function to call with the plugin element when the plugin starts. |
| `class` | CSS classes to toggle on the element shortly after the plugin starts. |
| `aclass` | When truthy, adds the plugin name to the element as a CSS class. |
```html
```
```text
red 10 panel
init UI-PLUGIN
```
The element ends up with the classes `panel loaded`.
## Lifecycle
1. The callback of `PLUGIN()` runs. Assign methods and register watchers here.
2. `exports.make()` runs, if defined, when the instance is ready.
3. `exports.destroy()` runs, if defined, when the plugin is removed.
The library looks for removed elements once per minute. `FREE()` runs that clean-up at once:
```js
PLUGIN('chart', function(exports) {
exports.destroy = function() {
console.log('destroy');
};
});
$('#area').empty();
console.log(typeof PLUGINS.chart); // object
FREE(); // destroy
console.log(typeof PLUGINS.chart); // undefined
```
## One declaration, several instances
When the `path` attribute has two words, the first is the path of the instance and the second is the name of the declaration. Use `?` as the first word to get a generated path.
```html
```
`left.value` is `4` and `right.value` is `5`. Each instance keeps its own data. The third instance has a unique path that starts with `jComponent.data.`.
## The common plugin
The name `*` is a shortcut for the plugin `common`, a convenient place for what the whole application shares:
```html
```
## Nested plugins
A plugin can live inside another plugin. `?` in its `path` is replaced by the path of the parent, `?1` in its markup points one plugin up, and `exports.parent` returns the parent instance.
```html
/
```
The inner plugin renders `Ann / A-100`, and the data is `{"number":"A-100","customer":{"name":"Ann"}}`.
## Loading data from a server
`exports.ajax(url, [data], [callback])` sends a request. When the last argument is a string, the response is written to that path of the plugin:
```js
PLUGIN('products', function(exports) {
exports.make = function() {
// Writes the response to "products.items"
exports.ajax('GET /api/products/', 'items');
exports.ajax('GET /api/products/', function(response) {
console.log(response.length);
});
};
});
```
## Dependencies
The last argument of `PLUGIN()` lists what must be ready before the plugin starts. It is a comma-separated string of URLs or an array of URLs and functions. A function receives a `next` callback.
```js
var loadmaps = function(next) {
window.MAPS = { ready: true };
next();
};
PLUGIN('map', function(exports) {
console.log(window.MAPS.ready); // true
}, ['/js/geo.js', loadmaps]);
```
URLs are loaded with `IMPORT()`. To load a whole plugin from a file, see [Importing content](../importing/).
---
title: Importing content
project: jComponent V20
version: 20.015
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/guides/importing/
updated: 2026-11-22T18:41:57.302Z
---
# Importing content
> How to load scripts, stylesheets and HTML parts into a running page with IMPORT() and the ui-import element.
An application does not have to load everything at start. `IMPORT()` loads a script, a stylesheet or a part of a page when it is needed, and the `` element does the same from the markup.
## IMPORT()
`IMPORT(url, [target], [callback], [prepare])` decides what to do from the extension of the URL:
| Extension | Result |
| --- | --- |
| `.js` | Adds a `
```
```html
```
```text
plugin invoice
init
```
The element `#title` contains the text `invoice`, `` has the class `ready`, and the instance is available as `PLUGINS.invoice`. Read more about plugins in [Plugins](../plugins/).
## Knowing when content is imported
The global event `import` is emitted after each import with the URL and the target. For a script or a stylesheet, the second argument is the new element:
```js
ON('import', function(url, target) {
console.log(url);
});
```
## Requests made for HTML
HTML is downloaded with `AJAX()`, so the request carries the language set in `DEF.language`, and a URL ending with `.html` also carries `DEF.version`. See [Localization](../localization/).
---
title: Templates with Tangular
project: jComponent V20
version: 20.015
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/guides/tangular/
updated: 2026-11-18T13:55:34.124Z
---
# Templates with Tangular
> How to write templates with Tangular: values, conditions, loops and helpers.
Tangular is the template engine included in the library. It turns a template and a data object into an HTML string. Templates are compiled to JavaScript functions, so one template can render many times.
## Rendering a template
`Tangular.render(template, [model], [repository], [helpers])` compiles and renders in one step. `Tangular.compile(template)` returns a function to use repeatedly.
```js
var html = Tangular.render('{{ title }} {{ user.name }}
', { title: 'Team', user: { name: 'Ann' } });
console.log(html);
var template = Tangular.compile('Hello {{ name }}!');
console.log(template({ name: 'Ann' }));
console.log(template({ name: 'Bob' }));
```
```text
Team Ann
Hello Ann!
Hello Bob!
```
A compiled template is called as `template(model, [repository], [helpers])`. `Ta` is a short alias of `Tangular`.
## Values
`{{ name }}` prints a value of the model. The output is HTML-encoded. The `raw` helper prints the value as it is, so use it only for HTML you trust.
```js
var model = { name: 'Ann ', age: 30, user: { address: null }, score: 0, note: null };
Tangular.render('{{ name }}', model); // <b>Ann</b>
Tangular.render('{{ name | raw }}', model); // Ann
Tangular.render('[{{ user.address.city }}]', model); // []
Tangular.render('{{ score }}|{{ note }}|{{ age + 1 }}|{{ name.length }}', model); // 0||31|10
Tangular.render('{{ age > 18 ? "adult" : "minor" }}', model); // adult
```
A missing value prints nothing, and so does `null`. The number `0` is printed. A tag can hold a JavaScript expression over the values of the model.
## Conditions
A condition starts with `{{ if }}` and ends with `{{ fi }}`. `{{ else if }}` and `{{ else }}` are optional.
```js
var template = Tangular.compile('{{ if age >= 65 }}senior{{ else if age >= 18 }}adult{{ else }}child{{ fi }}');
template({ age: 70 }); // senior
template({ age: 30 }); // adult
template({ age: 12 }); // child
```
A condition is plain JavaScript. Reading a property of a missing object is an error there, which is written to the console and leaves the result `undefined`. Check the object first:
```js
Tangular.render('{{ if user && user.active }}on{{ else }}off{{ fi }}', {}); // off
```
## Loops
`{{ foreach item in list }}` repeats its content until `{{ end }}`. `$index` holds the position of the current item.
```js
var model = {
tags: ['red', 'green', 'blue'],
sizes: { s: 10, m: 20 },
groups: [{ name: 'A', items: [1, 2] }, { name: 'B', items: [3] }]
};
Tangular.render('{{ foreach tag in tags }}{{ $index }}:{{ tag }} {{ end }}', model);
// 0:red 1:green 2:blue
Tangular.render('{{ foreach m in sizes }}{{ m.key }}={{ m.value }} {{ end }}', model);
// s=10 m=20
Tangular.render('{{ foreach g in groups }}{{ g.name }}({{ foreach n in g.items }}{{ n }}{{ end }}) {{ end }}', model);
// A(12) B(3)
```
An object is looped as a list of items with `key` and `value`. A missing or empty list renders nothing.
`{{ continue }}` skips to the next item and `{{ break }}` ends the loop:
```js
Tangular.render('{{ foreach tag in tags }}{{ if $index === 1 }}{{ continue }}{{ fi }}{{ tag }} {{ end }}', model);
// red blue
Tangular.render('{{ foreach tag in tags }}{{ if $index === 2 }}{{ break }}{{ fi }}{{ tag }} {{ end }}', model);
// red green
```
Nested loops share one `$index`. After an inner loop finishes, `$index` keeps the last position of that inner loop until the outer loop moves on, so read the outer position ahead of the inner loop:
```js
var model = { groups: [{ items: ['a', 'b', 'c'] }, { items: ['d'] }] };
Tangular.render('{{ foreach g in groups }}{{ $index }}:{{ foreach n in g.items }}{{ n }}{{ end }}:{{ $index }} {{ end }}', model);
// 0:abc:2 1:d:0
```
## Helpers
A helper transforms a value. It follows the value after a `|`, and helpers can be chained.
| Helper | Description |
| --- | --- |
| `raw` | Prints the value without encoding. |
| `encode([type])` | Encodes for HTML. The types `url`, `json`, `json2` and `querify` select another output. |
| `format(...)` | Formats a number or a date. |
| `pluralize(zero, one, few, other)` | Selects a text by a number. |
| `empty([text])`, `def([text])` | Prints `text` or `DEF.empty` for an empty value. |
| `currency([name])` | Formats a number with a currency from `DEF.currencies`. |
| `cl(name, [key])` | Finds a label in the code list `DEF.cl[name]` by `id`. |
The arguments of each helper are described in [Tangular helpers](../../reference/tangular-helpers/).
```js
DEF.currencies.eur = function(value) {
return value.format(2) + ' EUR';
};
DEF.cl.status = [{ id: 1, name: 'Open' }, { id: 2, name: 'Closed' }];
var model = {
price: 1234.5,
created: new Date(2026, 0, 15, 10, 5),
count: 3,
note: '',
status: 2,
query: 'a b&c',
data: { a: 1 }
};
```
| Template | Output |
| --- | --- |
| `{{ price \| format(2) }}` | `1 234.50` |
| `{{ created \| format("yyyy-MM-dd HH:mm") }}` | `2026-01-15 10:05` |
| `{{ count \| pluralize("no items", "# item", "# items", "# items") }}` | `3 items` |
| `{{ note \| empty }}` | `---` |
| `{{ note \| empty("n/a") }}` | `n/a` |
| `{{ price \| currency("eur") }}` | `1 234.50 EUR` |
| `{{ status \| cl("status") }}` | `Closed` |
| `{{ query \| encode("url") }}` | `a%20b%26c` |
| `{{ data \| encode("json") }}` | `{"a":1}` |
## Custom helpers
`Tangular.register(name, callback)` adds a helper for all templates. The first argument of the callback is the value, the next ones come from the template, and `this` is the model.
```js
Tangular.register('initials', function(value) {
return value.split(' ').map(function(word) {
return word.charAt(0);
}).join('');
});
Tangular.register('wrap', function(value, before, after) {
return before + value + after;
});
Tangular.register('fullname', function(value) {
return this.first + ' ' + value;
});
var model = { name: 'Ann Lee', first: 'Ann', last: 'Lee', html: '' };
Tangular.render('{{ name | initials }}', model); // AL
Tangular.render('{{ name | initials | wrap("[", "]") }}', model); // [AL]
Tangular.render('{{ last | fullname }}', model); // Ann Lee
```
The output of a helper is not encoded. Add `encode` at the end of the chain when the value comes from a user:
```js
Tangular.render('{{ html | wrap("", "") }}', model); //
Tangular.render('{{ html | wrap("", "") | encode }}', model); // <i>
```
Helpers for one call only go to the last argument of `render()`:
```js
var helpers = { shout: function(value) { return value + '!'; } };
Tangular.render('{{ first | shout }}', model, null, helpers); // Ann!
```
## The repository
The repository is a second object for values that do not belong to the model. Templates read it through `$`:
```js
var repository = { title: 'Users', limit: 2 };
Tangular.render('{{ $.title }}: {{ name }}', { name: 'Ann' }, repository);
// Users: Ann
var template = Tangular.compile('{{ foreach n in items }}{{ if $index < $.limit }}{{ n }} {{ fi }}{{ end }}');
template({ items: ['a', 'b', 'c'] }, repository);
// a b
```
## Custom delimiters
`Tangular.compile(template, begin, end)` replaces `{{` and `}}`. Both values are parts of a regular expression, so special characters need escaping:
```js
var template = Tangular.compile('[[ name ]] and {{ other }}', '\\[\\[', '\\]\\]');
template({ name: 'Ann' }); // Ann and {{ other }}
```
## Line breaks
A line break directly in front of a tag and at the end of the template is removed:
```js
Tangular.render('a\n{{ name }}\nb\n', { name: 'X' }); // "aX\nb"
```
## Templates in the page
The `template` command of `` renders a Tangular template with the value of a path. Inside the template, the value is available as `value`, and the template renders again when the value changes.
```html
```
The element renders ``. More about bindings is in [Data binding](../data-binding/).
---
title: Routing
project: jComponent V20
version: 20.015
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/guides/routing/
updated: 2026-11-18T13:55:39.124Z
---
# Routing
> How to map URLs to functions in a single-page application with ROUTE(), REDIRECT() and NAV.
Routing lets one HTML page behave like many. The library watches the URL, runs the function registered for it, and changes the URL without reloading the page. The server must return the same application page for every URL the application uses, so that opening a link directly works too.
## Declaring routes
`ROUTE(url, callback, [middleware], [init])` registers a route. Parts in curly brackets are dynamic, and their values are passed to the callback in order. `REDIRECT(url)` navigates to a URL.
```js
ROUTE('/', function() {
console.log('home');
});
ROUTE('/products/', function() {
console.log('list');
});
ROUTE('/products/new/', function() {
console.log('form');
});
ROUTE('/products/{id}/', function(id) {
console.log('detail', id);
});
ROUTE('/products/{id}/{tab}/', function(id, tab) {
console.log('tab', id, tab, this.url);
});
ON('ready', function() {
setTimeout(function() {
REDIRECT('/products/');
REDIRECT('/products/new/');
REDIRECT('/products/AB-15/');
REDIRECT('/products/15/photos');
}, 300);
});
```
```text
home
list
form
detail AB-15
tab 15 photos /products/15/photos/
```
The route for the current URL runs when the application starts. Inside the callback, `this` is `NAV`. A URL gets a trailing slash when it has none, and a static route such as `/products/new/` wins over a dynamic one such as `/products/{id}/`.
The URL is compared in lowercase, so write the routes in lowercase. A route with a capital letter never matches. The values of dynamic parts keep their case:
```js
ROUTE('/team/{name}/', function(name) {
console.log(name);
});
REDIRECT('/TEAM/AnnLee/'); // AnnLee
```
## Reading the current location
```js
ROUTE('/search/', function() {
console.log(JSON.stringify(NAV.query));
console.log(NAV.url, '|', NAV.href, '|', NAV.queryraw);
});
REDIRECT('/search/?q=lamp&page=2');
```
```text
{"q":"lamp","page":"2"}
/search/ | /search/?q=lamp&page=2 | q=lamp&page=2
```
| Property | Description |
| --- | --- |
| `NAV.url` | The current path without the query string. |
| `NAV.href` | The URL passed to the last navigation. |
| `NAV.query` | The parsed query string. All values are strings. |
| `NAV.queryraw` | The query string without the leading `?`. |
| `NAV.params` | An array with the values of the dynamic parts. |
| `NAV.is404` | `true` when no route matches the current URL. |
| `NAV.history` | An array of the previous URLs. |
| `NAV.isback` | The number of URLs to go back to. |
| `NAV.isforward` | The number of URLs to go forward to. |
`NAV` is a normal path, so the markup can bind to it:
```html
```
## Links
A plain link reloads the page. `NAV.clientside(selector)` turns matching links into client-side navigation. The URL is read from `href`, `data-href` or `data-url`. Any element with the class `exec` and a `data-href` attribute navigates too.
```html
About
Contact
Help
```
## Moving through the history
| Method | Description |
| --- | --- |
| `NAV.back()` | Goes to the previous URL. |
| `NAV.forward()` | Goes to the next URL after going back. |
| `NAV.prev()` | Returns the previous URL. |
| `NAV.next()` | Returns the next URL. |
| `NAV.refresh()`, `NAV.reload()` | Runs the route of the current URL again. |
```js
REDIRECT('/a/');
REDIRECT('/a/b/');
console.log(NAV.url, NAV.prev()); // /a/b/ /a/
NAV.back();
console.log(NAV.url, NAV.next()); // /a/ /a/b/
NAV.forward();
console.log(NAV.url); // /a/b/
REDIRECT('../');
console.log(NAV.url); // /a/
```
`REDIRECT('../')` goes one level up. The buttons of the browser work as well.
`NAV.autosave()` keeps the history in the browser storage at each navigation, `NAV.save()` stores it once, and `NAV.load()` restores it:
```js
NAV.autosave();
REDIRECT('/a/');
REDIRECT('/b/');
NAV.history.length = 0;
NAV.load();
console.log(JSON.stringify(NAV.history)); // ["/","/a/"]
```
## Middleware
A middleware runs ahead of the route callback and decides if the route continues. `MIDDLEWARE(name, callback)` registers one, and the third argument of `ROUTE()` selects them.
```js
MIDDLEWARE('auth', function(next, options, roles, route) {
console.log('auth', JSON.stringify(options), roles.join(), route.id);
if (window.user)
next();
else
next(false);
});
ROUTE('/admin/', function() {
console.log('admin page');
}, ['auth', '@admin', '@editor', { title: 'Admin' }]);
```
With no user, the first navigation prints only the `auth` line. Once `window.user` is set, the next one reaches the page:
```text
auth {"title":"Admin"} admin,editor /admin/
auth {"title":"Admin"} admin,editor /admin/
admin page
```
The middleware argument of `ROUTE()` is an array or a comma-separated string:
| Value | Meaning |
| --- | --- |
| `name` | The name of a middleware. |
| `@name` | A role, passed to the middleware in `roles`. |
| `#name` | A code list to load with `CL()`. |
| An object | Options, passed to the middleware in `options`. Only in an array. |
`next()` continues with the next middleware. `next(false)` and `next(new Error())` stop the route. The route callback does not run either when the user navigates elsewhere while a middleware is still working.
```js
MIDDLEWARE('first', function(next) { console.log('first'); next(); });
MIDDLEWARE('second', function(next) { console.log('second'); next(); });
CLINIT('countries', function(next) {
console.log('loading countries');
next([{ id: 'sk', name: 'Slovakia' }]);
});
ROUTE('/orders/', function() {
console.log('orders', DEF.cl.countries.length);
}, 'first,second,#countries');
```
```text
first
second
loading countries
orders 1
```
`MIDDLEWARE(names, callback)` with an array of names runs those middleware outside of any route and then calls the callback:
```js
MIDDLEWARE(['first', 'second'], function() {
console.log('both done');
});
```
## Preparing a route once
The `init` function runs once, on the first visit of a route, and receives a `next` callback. It suits work such as downloading the part of the application that the route needs.
```js
ROUTE('/reports/', function() {
console.log('reports');
}, function(next) {
console.log('prepare once');
next();
});
REDIRECT('/reports/');
REDIRECT('/');
REDIRECT('/reports/');
```
```text
prepare once
reports
reports
```
When a route also has middleware, `init` is the fourth argument of `ROUTE()`.
## Events
| Event | Arguments | Description |
| --- | --- | --- |
| `location` | `url` | The URL changes. Emitted ahead of the route callback. |
| `404` | | No route matches the URL. |
| `route` | `url` | A new route is registered. |
```js
ON('location', function(url) {
console.log('location', url);
});
ON('404', function() {
console.log('not found', NAV.url, NAV.is404);
});
REDIRECT('/missing/');
```
```text
location /missing/
not found /missing/ true
```
## Adding and removing routes at runtime
A route registered while its URL is showing the 404 state runs immediately, so a route can arrive later from an imported file. `NAV.remove(url)` removes a route.
```js
REDIRECT('/missing/');
ROUTE('/missing/', function() {
console.log('added later');
});
console.log(NAV.is404); // false
NAV.remove('/missing/');
```
## Keeping a query parameter
`NAV.remember(name, value)` adds a parameter to every following `REDIRECT()`. Passing `null` as the value stops it.
```js
NAV.remember('lang', 'de');
REDIRECT('/list/');
console.log(NAV.href); // /list/?lang=de
NAV.remember('lang', null);
REDIRECT('/list/');
console.log(NAV.href); // /list/
```
## Routing with hashes
With `NAV.hashtags = true`, routes are driven by the hash part of the URL. Set it at the start of the application, write the routes with a leading `#`, and navigate with links or `location.hash`.
```js
NAV.hashtags = true;
ROUTE('#inbox', function() {
console.log('inbox', NAV.url);
});
ROUTE('#sent', function() {
console.log('sent', NAV.url);
});
location.hash = '#inbox'; // inbox #inbox
```
## Routing without changing the address bar
`NAV.custom()` keeps all navigation inside the application. Routes and `REDIRECT()` work as usual, and the address bar stays as it is. This is useful for an application embedded in another page. Call it at the start of the application.
```js
NAV.custom();
ROUTE('/', function() {
console.log('home');
});
```
---
title: Forms and validation
project: jComponent V20
version: 20.015
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/guides/forms/
updated: 2026-11-18T13:55:39.124Z
---
# Forms and validation
> How to build a form from components, validate it, show errors, submit it and reset it.
A form is a group of components bound to paths under one object, for example `form.name` and `form.email`. Each component keeps its own state: whether the user touched it, changed it, and whether its value is valid. This guide builds a form step by step. How to write components in general is explained in [Creating components](../creating-components/).
## A field with validation
A component takes part in validation when it defines `self.validate`. The function receives the value and runs each time the value changes.
```html
```
`self.autobind20()` connects the ` ` to the path. When the user writes `ann` into the email field and leaves it, the model is `{"email":"ann"}` and the message `Enter a valid email address` appears.
The result of `self.validate` sets `config.invalid`:
| Result | Meaning | `config.invalid` |
| --- | --- | --- |
| `true` or an empty string | Valid | `false` |
| A non-empty string | Invalid, with a message | The message |
| Anything else | Invalid | `true` |
## Field state
| Value | CSS class | Set when |
| --- | --- | --- |
| `config.touched` | `ui-touched` | The user typed into the field or left it. |
| `config.modified` | `ui-modified` | The user changed the value. |
| `config.invalid` | `ui-invalid` | The value did not pass the validation. |
| `config.disabled` | `ui-disabled` | The component is disabled. |
The library keeps the classes on the `` element up to date and calls `self.state()` after each change of the state.
A required empty field is invalid from the moment the page loads. Testing `config.touched` as in the example above keeps the message hidden until the user has worked with the field.
## Checking the form
`ERRORS(path, callback)` returns the invalid components under a path. It also accepts a jQuery element and searches inside it. `COMPONENTS(path)` returns the components that match the flags in the path.
```html
```
```text
form.name - This field is required
form.email - This field is required
2
2
1
2
0
```
`COMPONENTS()` understands the flags `@invalid`, `@valid`, `@touched`, `@modified`, `@required`, `@disabled`, `@enabled`, `@visible` and `@hidden`. `ERRORS('form @visible', callback)` skips the fields that are hidden.
## Disabling the submit button
Watch the form, keep the result in a path, and let `` disable the button:
```html
Save
```
The button is disabled while the name is empty and becomes enabled after `SET('form.name', 'Ann')`.
## Submitting
Check the errors, send `GET('form')`, and reset the form after success. The `@change` flag marks the fields as touched and modified, which reveals their messages when the user submits too early.
```js
function submit() {
ERRORS('form', function(components) {
if (components.length) {
SET('form @change', GET('form'));
return;
}
AJAX('POST /api/contact/', GET('form'), function(response) {
if (response.success)
SET('form @reset', {});
});
});
}
```
## Resetting and filling the form
| Call | Effect |
| --- | --- |
| `SET('form.name @change', value)` | Sets the value and marks the field as touched and modified. |
| `RESET('form')` | Clears the touched and modified state and keeps the values. |
| `SET('form @reset', data)` | Replaces the data and clears the state. Use it to load a record into a form. |
| `SET('form @default', {})` | Replaces the data, clears the state and applies the default values. |
A default value is a JavaScript expression in the `default` attribute of the component. It is applied at start and by the `@default` flag whenever the value is empty.
```html
```
```text
@change {"country":"Slovakia","name":"Ann"} 1 1
RESET {"country":"Slovakia","name":"Ann"} 0 0
@reset {"name":"Bob","country":"Austria"} 0 0
@default {"country":"Slovakia"} 0 0
```
More flags are described in [Flags and path modifiers](../flags/).
## Converting the value
The `type` key of the configuration converts the text from the ` ` when `autobind20()` writes it to the model. With `type:number`, typing `42` stores the number `42`:
```html
```
## A field that is required on a condition
The `required` command of `` sets `config.required` on the components inside it. Call `self.validate2()` from `self.configure` to validate again when the option changes:
```html
```
The empty field is valid at first. After `SET('form.company', true)` it is required and invalid, and after `SET('form.company', false)` it is valid again.
## Forms inside a plugin
A [plugin](../plugins/) is a natural home for a form. The fields use `?` paths, `exports.set('@reset', data)` fills the form, and `exports.form` returns the data and clears the state of the fields.
```html
```
Calling `EXEC('contact/save')` on the empty form prints `errors 1`. After `EXEC('contact/load', { name: 'Ann' })` and `SET('contact.name @change', 'Anna')`, it prints `errors 0` and `{"name":"Anna"}`.
---
title: Localization
project: jComponent V20
version: 20.015
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/guides/localization/
updated: 2026-11-18T13:55:39.124Z
---
# Localization
> How to translate texts and adapt dates, numbers and currencies to a language.
Localization has two parts: translating the texts of the application, and showing dates, numbers and currencies the way the user expects.
## Marking and translating texts
A translatable text is written as `@(text)`. `LOCALIZE(text)` loads a dictionary and `TRANSLATE(text)` replaces the marked texts in a string.
The key of a dictionary entry is the hash of the original text in base 36, created with `HASH(text).toString(36)`. Each line of the dictionary has the form `key : translation`, and lines starting with `//` are comments.
```js
var key = HASH('Save changes').toString(36);
console.log(key);
LOCALIZE([
'// German',
key + ' : Änderungen speichern',
HASH('Time').toString(36) + ' : Zeit: 10:30'
].join('\n'));
console.log(TRANSLATE('@(Save changes) '));
console.log(TRANSLATE('@(Time) / @(Not translated)'));
console.log(JSON.stringify(DEF.dictionary));
```
```text
bqgoqo
Änderungen speichern
Zeit: 10:30 / Not translated
{"bqgoqo":"Änderungen speichern","1jvfx":"Zeit: 10:30"}
```
A text without a translation keeps its original wording. Keys may also start with the letter `T`, as in the resource files of the Total.js framework. Loaded entries are kept in `DEF.dictionary`, and each call to `LOCALIZE()` adds to them.
## Loading a dictionary from a file
```js
AJAX('GET /locale/de.resource', function(text) {
LOCALIZE(text);
console.log(TRANSLATE('@(Close)')); // Schliessen
});
```
## Where texts are translated
Content loaded with `IMPORT()` and `` is translated automatically, so load the dictionary first. The static HTML of the page is not translated.
```html
@(Save)
```
A component translates its own markup by calling `TRANSLATE()`:
```js
COMPONENT('savebutton', function(self) {
self.make = function() {
self.html(TRANSLATE('@(Save) '));
};
});
```
More about loading content is in [Importing content](../importing/).
## Sending the language to the server
`DEF.language` is added to the URL of every `AJAX()` request, unless the URL already contains the parameter. `DEF.languagekey` is the name of the parameter, and the default is `language`. `ENVIRONMENT(name, version, language)` sets the storage name, the version and the language in one call.
```js
ENVIRONMENT('myapp', '1.5', 'de');
AJAX('GET /api/products/', NOOP);
AJAX('GET /parts/menu.html', NOOP);
AJAX('GET /api/products/?language=en', NOOP);
```
The requests go to these addresses:
```text
/api/products/?language=de
/parts/menu.html?version=1.5&language=de
/api/products/?language=en
```
## Dates
`MONTHS` and `DAYS` hold the names used by `Date.format()`, and `DEF.dateformat` is the format used when no format is given. `DAYS` starts with Sunday.
```js
MONTHS[0] = 'Januar';
DAYS[1] = 'Montag';
DEF.dateformat = 'dd.MM.yyyy';
var date = new Date(2026, 0, 5, 14, 3);
date.format(); // 05.01.2026
date.format('dddd, d. MMMM yyyy'); // Montag, 5. Januar 2026
date.format('HH:mm'); // 14:03
```
The tokens of the format are listed in [Date](../../reference/date/).
## Numbers
`DEF.thousandsseparator` and `DEF.decimalseparator` control `Number.format()`:
```js
DEF.thousandsseparator = '.';
DEF.decimalseparator = ',';
(1234567.891).format(2); // 1.234.567,89
```
## Currencies
`DEF.currencies` holds a formatting function for each currency, and `DEF.currency` is the default one. `Number.currency()` and the Tangular helper `currency` use them.
```js
DEF.currencies.eur = function(value) {
return value.format(2) + ' €';
};
DEF.currency = 'eur';
(1234.5).currency(); // 1.234,50 €
(1234.5).currency('eur'); // 1.234,50 €
Tangular.render('{{ price | currency }}', { price: 99 }); // 99,00 €
```
The output above uses the separators from the previous section.
## Plural forms
`Number.pluralize(zero, one, few, other)` selects a text by the number. `few` applies to the numbers from 2 to 4, and `other` to the rest. `#` is replaced by the number and `##` by the formatted number.
```js
var text = function(count) {
return count.pluralize('No files', '# file', '# files (few)', '# files');
};
text(0); // No files
text(1); // 1 file
text(3); // 3 files (few)
text(5); // 5 files
(1500).pluralize('none', 'one', 'few', '## files'); // 1 500 files
```
In a template, the same function is available as the helper `pluralize`. See [Templates with Tangular](../tangular/).
---
title: Global functions
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/globals/
updated: 2026-11-18T13:58:14.460Z
---
# Global functions
> The functions and variables that the library adds to the window object.
The library adds these functions and variables to `window`, so they are available everywhere in your code. Start with [Paths](../../guides/paths/) and [Data binding](../../guides/data-binding/) to see how they work together.
## API
### ADAPT(path, id, text)
Type: `method`
Prepares a piece of HTML for a specific path and identifier.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The value for `~PATH~` and `CLASS`. Use `null` to skip these replacements. |
| `id` | `String` | yes | | The value for `~ID~`. Use `null` to skip this replacement. |
| `text` | `String` | yes | | The text to prepare. |
Returns: `String` The prepared text.
The method translates `@(text)` markup, applies `--name--` variables and replaces `~CDN~` with [DEF.cdn](../def/). When `path` is set, `~PATH~` and `CLASS` become the path, `` elements without a `path` attribute receive it, and the first `PLUGIN(function(` becomes `PLUGIN('path', function(`. When `id` is set, `~ID~` becomes the identifier. A `text` that is empty or is not a string is returned unchanged.
Example: Replace the keywords
```js
var html = '~PATH~
';
console.log(ADAPT('users', 'u1', html)); // users
```
### AJAX(url, [data], callback, [onprogress], [scope], [id])
Type: `method`
Sends an HTTP request and delivers the response to a function or a path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes | | The method, the address and optional keywords, for example `POST /api/users/ ERROR`. |
| `data` | `Object` | no | | The request body: an object sent as JSON, a string sent as form data, or `FormData`. |
| `callback` | `Function|String` | yes | | A function that receives the response, or a path that receives it. |
| `onprogress` | `Function|String` | no | | A function or a path that receives the upload percentage. |
| `scope` | `Object` | no | `window` | The object in which a `callback` path is resolved. |
| `id` | `String` | no | `url` | The key used by `SYNC` and by the cache. |
The `url` starts with the HTTP method, followed by the address and optional keywords separated by spaces:
| Keyword | Meaning |
| --- | --- |
| `ERROR` | Passes the response through [ERROR()](../globals/). If it holds an error, the `ERROR` event is emitted and `callback` does not run. An error status without a response body emits the `ERROR` event with the status code. |
| `SYNC` | Queues requests with the same `id`, so that they run one after another. |
| `<1 minute>` | Caches the response for the given time with [CACHE()](../globals/), unless it is an error. While the request is pending, other calls with the same `id` wait for its response, so only one request is sent. |
| `#name` | Loads the code list `name` first. See [CL()](../globals/). |
| `@flag` | Emits the flag when the request is sent. See [Flags and path modifiers](../../guides/flags/). |
An object in `data` is sent as JSON, a string is sent as it is with the content type `application/x-www-form-urlencoded`, and `FormData` is sent as a form.
A status code of 400 or higher counts as an error. A request that cannot reach the server, is aborted or runs out of time has the status code `0`, and `callback` receives an empty response. A response with a JSON content type is parsed with [PARSE()](../globals/). Every request adds the headers from [DEF.headers](../def/). When [DEF.language](../def/) is set, it is added to the query string. When [DEF.version](../def/) is set, it is added to the query string of `.html` addresses.
The `request` and `response` [events](../events/) let you inspect or change each call. Once the request is sent, `options.xhr` in the `request` event holds its `XMLHttpRequest`, so `options.xhr.abort()` stops it. `UPLOAD()` is the same function under another name.
Example: Read a response
```js
AJAX('GET /api/users/', function(response) {
console.log(response.length); // 2
});
```
Example: Store a response in a path
```js
AJAX('POST /api/orders/', { amount: 10 }, 'orders.last');
WATCH('orders.last', function(value) {
console.log(value.id); // 100
});
```
Example: Send form data
```js
AJAX('POST /api/login/', 'name=Ann&remember=1', function(response) {
console.log(response.ok); // true
});
```
Example: Stop a request
```js
var request;
ON('request', options => request = options);
ON('ERROR', status => console.log('failed', status)); // failed 0
AJAX('GET /api/report/ ERROR', NOOP);
request.xhr.abort();
```
### API(url, name, [data], callback, [scope])
Type: `method`
Calls a Total.js API endpoint on a specific address.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes | | The address of the endpoint. |
| `name` | `String` | yes | | The name of the operation, optionally followed by keywords. |
| `data` | `Object` | no | | The data of the operation. |
| `callback` | `Function|String` | yes | | A function or a path that receives the response. |
| `scope` | `Object` | no | `window` | The object in which a `callback` path is resolved. |
The method sends `POST url` with the JSON body `{ schema: name, data: data }`. Keywords accepted by [AJAX()](../globals/) can follow the name, for example `users_list ERROR`. To use one fixed address, see [TAPI()](../globals/) and [PIPE()](../globals/).
Example: Call an operation
```js
API('/admin/api/', 'users_read', { id: 5 }, function(response) {
console.log(response.name); // Peter
});
```
### APPEARANCE(options)
Type: `method`
Sets the colour scheme of the page through CSS variables and body classes.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | yes | | The switches and the CSS variables. |
Every key becomes a CSS variable on `:root`, except the four switches below. The `color` key also updates [DEF.color](../def/) and adds the variable `--rgb` with the red, green and blue values of a hexadecimal colour with three or six digits.
| Key | Meaning |
| --- | --- |
| `dark` or `darkmode` | Toggles the class `ui-dark` on the body. |
| `large` or `largemode` | Toggles the class `ui-large` on the body. |
The class prefix comes from [DEF.prefixcsslibrary](../def/).
Example: Dark theme with an accent colour
```js
APPEARANCE({ dark: true, color: '#4285F4' });
console.log($('#cssappearance').html()); // :root{--color:#4285F4;--rgb:66,133,244}
console.log($('body').hclass('ui-dark')); // true
```
Example: A short colour
```js
APPEARANCE({ color: '#abc' });
console.log($('#cssappearance').html()); // :root{--color:#abc;--rgb:170,187,204}
```
### ASETTER(name, [a], [b], [c], [d])
Type: `method`
Creates a function that calls a component method later.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The selector and the method, in the same form as in `SETTER()`. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
Returns: `Function` A function without arguments.
Each call of the returned function runs [SETTER()](../globals/) with the arguments given here.
Example: Prepare a call
```html
```
### ATTRD(element, [name])
Type: `method`
Reads a `data-*` attribute from an element or from its closest parent that has it.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery|Event|Element|Object` | yes | | The starting point. |
| `name` | `String` | no | `id` | The attribute name without the `data-` prefix. |
Returns: `String` The value of the attribute.
The `element` can be a jQuery object, a jQuery event (its `currentTarget` is used) or a DOM element. For a plain object, the method returns the property `name`. Any other value is returned as it is.
Example: Read the closest identifier
```html
Save
```
### BLOCKED(key, timeout, [callback])
Type: `method`
Limits how often an operation can run.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes | | The name of the operation. |
| `timeout` | `Number|String` | yes | | The time in milliseconds, or a text such as `5 minutes`. |
| `callback` | `Function` | no | | A function that runs when the operation is not blocked. |
Returns: `Boolean` `true` when the operation is blocked.
The first call blocks `key` for the given time and returns `false`. Further calls return `true` until the time passes. A block of 10 seconds or longer is kept in `localStorage`, so it survives a page reload.
Example: Allow one click per second
```js
ON('ready', function() {
console.log(BLOCKED('save', 1000)); // false
console.log(BLOCKED('save', 1000)); // true
});
```
### CACHE(key, [value], [expire])
Type: `method`
Reads or writes a value in the persistent cache.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes | | The key. |
| `value` | `Object` | no | | The value to store. |
| `expire` | `String` | no | | The lifetime of the value, or `session`. |
Returns: `Object` The stored value when reading, otherwise nothing.
With `expire`, the method stores the value. Without it, the method returns the stored value, or `null` when the value is missing or has expired. The value `session` keeps the data in memory until the page is closed. Any other value is a time such as `10 minutes`, `2 hours`, `1 day`, `1 week`, `1 month` or `1 year`, and the data is saved through [DEF.onstoragesave](../def/).
The cache is loaded when the library starts, so use it from the `ready` [event](../events/) onward.
Example: Write and read
```js
ON('ready', function() {
CACHE('filter', { page: 2 }, '1 day');
console.log(CACHE('filter')); // {"page":2}
console.log(CACHE('missing')); // null
});
```
### CACHEPATH(path, expire, [def])
Type: `method`
Keeps the value of a path in the cache between visits.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path. |
| `expire` | `String` | yes | | The lifetime of the saved value, for example `1 day`. |
| `def` | `Object|Function` | no | | The value used when nothing is saved. A function is called to get it. |
The method saves every change of the path with [CACHE()](../globals/) for the time in `expire`. When the path is empty, the saved value is written to it, and when nothing is saved, `def` is written. A path that already holds a value keeps it.
Called before the library has loaded the cache, the method waits for it and then restores the value. Plugins have the same method with a relative path: [plugin.cachepath()](../plugin/).
Example: Remember a filter
```js
CACHEPATH('filter.q', '1 day', 'all');
console.log(GET('filter.q')); // all
SET('filter.q', 'lamp');
// After a reload of the page, GET('filter.q') returns lamp
```
### CL(name, [callback])
Type: `method`
Loads code lists registered with `CLINIT()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | One name, or several names separated by commas. |
| `callback` | `Function` | no | | A function that runs when the lists are loaded. |
A code list is shared data, such as a list of countries, stored in [DEF.cl](../def/). A list is loaded once. The `callback` runs when all the lists are available. A name that is not registered yet is checked again every 500 milliseconds until it appears.
Example: Load a list on demand
```js
CLINIT('countries', function(next) {
next([{ id: 'SK', name: 'Slovakia' }]);
});
ON('ready', function() {
CL('countries', function() {
console.log(DEF.cl.countries.length); // 1
});
});
```
### clearTimeout2(name)
Type: `method`
Cancels a timer created with `setTimeout2()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the timer. |
Returns: `Boolean` `true` when the timer exists.
Example: Cancel a timer
```js
setTimeout2('search', NOOP, 1000);
console.log(clearTimeout2('search')); // true
console.log(clearTimeout2('unknown')); // false
```
### CLINIT(name, source, [init])
Type: `method`
Registers the source of a code list.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the code list. |
| `source` | `Function|String` | yes | | A function, a request or an operation. |
| `init` | `Boolean` | no | `false` | Loads the list immediately. |
When `source` is a function, it receives `next(value, [extend])`. Pass the list to `next()`. With `extend` set to `true`, `value` is an object whose keys are stored as separate code lists.
When `source` is a string, a value that starts with an HTTP method is loaded with [AJAX()](../globals/). Any other value is an operation for [TAPI()](../globals/).
Example: Load several lists at once
```js
CLINIT('all', function(next) {
next({ colors: ['red'], sizes: ['XL'] }, true);
}, true);
ON('ready', function() {
setTimeout(function() {
console.log(DEF.cl.colors, DEF.cl.sizes); // ["red"] ["XL"]
}, 100);
});
```
### CLONE(value, [raw])
Type: `method`
Creates a deep copy of a value.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object|String` | yes | | The value to copy, or a path. |
| `raw` | `Boolean` | no | `false` | Treats a string as a plain value. |
Returns: `Object` The copy.
A string is treated as a path to an object or an array, and the value found there is copied. With `raw` set to `true`, a string is returned as it is. Objects are copied through JSON, and dates inside them stay dates.
Example: Copy an object
```js
var a = { user: { name: 'Peter' } };
var b = CLONE(a);
b.user.name = 'Lucia';
console.log(a.user.name); // Peter
```
Example: Copy the value of a path
```js
SET('form', { name: 'Peter' });
var copy = CLONE('form');
console.log(copy); // {"name":"Peter"}
```
### CLRELOAD(name, [callback])
Type: `method`
Loads code lists again from their sources.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | One name, or several names separated by commas. |
| `callback` | `Function` | no | | A function that runs when the lists are reloaded. |
Only lists that are already loaded are reloaded. Other names are skipped.
Example: Refresh a list
```js
var counter = 0;
CLINIT('stats', function(next) {
next([++counter]);
});
ON('ready', function() {
CL('stats', function() {
CLRELOAD('stats', function() {
console.log(DEF.cl.stats); // [2]
});
});
});
```
### CMD(name, [a], [b], [c], [d])
Type: `method`
Runs a command on every component that registers it.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The command, optionally followed by flags. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
Components register commands with [command()](../component/). Flags can follow the name after a space, for example `CMD('refresh @saved')`: they are emitted first, as with [SET()](../globals/). To run a command only in a part of the page, use [$(selector).CMD()](../jquery/) or [plugin.cmd()](../plugin/).
Example: Clear every list
```html
```
### COMPONENT(name, [config], callback, [dependencies], [css])
Type: `method`
Registers a component declaration.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the component. |
| `config` | `String` | no | | The default configuration in the form `key:value;key:value`. |
| `callback` | `Function` | yes | | The declaration: `function(self, config, cls)`. |
| `dependencies` | `String|Array` | no | | Addresses to import first, separated by commas. An array can also contain functions that receive `next`. |
| `css` | `String` | no | | The styles of the component. |
The `callback` runs once for every instance, and receives the instance, its configuration and its CSS class. In the `css` argument, the word `CLASS` becomes `ui-` followed by the component name. See [Creating components](../../guides/creating-components/) and the [Component](../component/) object.
Example: Declare a component
```html
```
### COMPONENTS(path)
Type: `method`
Returns the components bound to a path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path, optionally with flags. |
Returns: `Array` The matching [component](../component/) instances.
The path includes everything below it, so `form` also returns a component bound to `form.name`. Flags in the path narrow the result: `@visible`, `@hidden`, `@touched`, `@modified`, `@required`, `@invalid`, `@valid`, `@disabled` and `@enabled`.
Example: Find the required fields
```html
```
### CONFIG(selector, config)
Type: `method`
Changes the configuration of existing and future components.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `selector` | `String|Function` | yes | | The components to configure. |
| `config` | `String|Object` | yes | | The configuration, as an object or in the form `key:value;key:value`. |
The `selector` can be:
| Selector | Matches |
| --- | --- |
| `name` | Components with this name. |
| `#id` | The component with this identifier. |
| `.path` | Components whose path contains `path`. |
| `*` | All components. |
| `a, b` | Several selectors separated by commas. |
| `function(instance)` | Components for which the function returns `true`. |
Example: Configure by name
```html
```
### COOKIES
Type: `property`
Reads and writes browser cookies.
Returns: `Object` The object with the methods.
The object has three methods:
| Method | Description |
| --- | --- |
| `COOKIES.get(name)` | Returns the value, or an empty string. |
| `COOKIES.set(name, value, [expire], [samesite])` | Writes a cookie for the path `/`. `expire` is a number of days, a `Date` or a text such as `1 day`. Without `expire`, the cookie is kept until the browser is closed. `samesite` is for example `lax`. |
| `COOKIES.rem(name)` | Removes the cookie. |
Example: Write and read a cookie
```js
COOKIES.set('theme', 'dark', '1 month', 'lax');
console.log(COOKIES.get('theme')); // dark
```
Example: Keep a cookie for a week
```js
COOKIES.set('token', 'a=1', 7);
console.log(COOKIES.get('token')); // a=1
```
### COPY(source, target)
Type: `method`
Copies the properties of one object to another.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `source` | `Object` | yes | | The object to read from. |
| `target` | `Object` | yes | | The object to write to. |
Returns: `Object` The `target` object.
Nested objects are cloned, so later changes in `source` do not affect `target`.
Example: Merge two objects
```js
var target = { a: 1 };
COPY({ b: { c: 2 } }, target);
console.log(target); // {"a":1,"b":{"c":2}}
```
### CSS(value, [id], [selector])
Type: `method`
Another name for `STYLE()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Array` | yes | | The CSS. |
| `id` | `String` | no | | The identifier of the style element. |
| `selector` | `String` | no | | A selector that prefixes every rule. |
See [STYLE()](../globals/). Setting `window.jc_globals = { CSS: false }` ahead of the library script leaves this global undefined.
### DAYS
Type: `property`
The English names of the days of the week, starting with Sunday.
Returns: `Array` Seven strings.
Example: Read a day
```js
console.log(DAYS[1]); // Monday
```
### DEF
Type: `property`
The default settings of the library.
Returns: `Object` The settings.
Described on its own page: [DEF](../def/).
### DECRYPT(text, [key], [type])
Type: `method`
Reads a value written by `ENCRYPT()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `text` | `String` | yes | | The text from `ENCRYPT()`. |
| `key` | `String` | no | | The key. |
| `type` | `String` | no | | The prefix of the text. |
Returns: `Object` The value, or `undefined`.
The `key` and the `type` must be the ones given to [ENCRYPT()](../globals/). The method returns `undefined` when the checksum does not match them, which is the case for a changed text. A value that starts with `[`, `{` or `"` is parsed as JSON.
Example: Read an object back
```js
var text = ENCRYPT({ id: 5 }, 'secret', 'U');
console.log(text.charAt(0)); // U
console.log(DECRYPT(text, 'secret', 'U')); // {"id":5}
console.log(DECRYPT(text, 'secret')); // undefined
```
### DIFFDOM(element, selector, html, [attribute])
Type: `method`
Updates the children of an element so that they match new HTML.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery` | yes | | The parent element. |
| `selector` | `String` | yes | | A selector of the compared children. |
| `html` | `String` | yes | | The new content. |
| `attribute` | `String` | no | | The attribute used for the comparison. |
Returns: `Object` The number of added, kept and removed elements: `{ add, upd, rem }`.
Children that have not changed stay in the DOM, so they keep their state. Children are compared by their whole HTML, or by the value of `attribute` when it is set.
Example: Update a list
```html
```
### EMIT(name, [a], [b], [c], [d])
Type: `method`
Emits an event.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the event. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
Handlers registered with [ON()](../globals/), and handlers registered on [components](../component/) and [plugins](../plugin/), receive the arguments. Flags can follow the name, for example `refresh @loading`. The events of the library are listed in [Events](../events/).
Example: Emit a custom event
```js
ON('saved', function(id, name) {
console.log(id, name); // 5 Peter
});
EMIT('saved', 5, 'Peter');
```
### EMPTYARRAY
Type: `property`
A frozen empty array.
Returns: `Array` An array that cannot be changed.
Example: A shared default value
```js
console.log(Object.isFrozen(EMPTYARRAY)); // true
```
### EMPTYOBJECT
Type: `property`
A frozen empty object.
Returns: `Object` An object that cannot be changed.
Example: A shared default value
```js
console.log(Object.isFrozen(EMPTYOBJECT)); // true
```
### ENCRYPT(value, [key], [type])
Type: `method`
Encodes a value as text with a checksum.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Object` | yes | | The value. |
| `key` | `String` | no | | The key of the checksum. |
| `type` | `String` | no | | A prefix written at the beginning of the text. |
Returns: `String` The encoded text.
An object or an array is serialized with [STRINGIFY()](../globals/) first. The result has the `type` as a prefix, the value in hexadecimal digits, the letter `x` and a checksum made with [HASH()](../globals/) from the value, the `key` and the `type`.
The value can be read back by anyone, so do not use the method to hide data: the key only lets [DECRYPT()](../globals/) find out whether the text was changed.
Example: Encode and decode
```js
var text = ENCRYPT('hello', 'secret');
console.log(text); // 68656c6c6fxds46dr
console.log(DECRYPT(text, 'secret')); // hello
console.log(DECRYPT(text, 'other')); // undefined
```
### ENV(name, [value])
Type: `method`
Reads or writes environment variables.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|Object` | yes | | The name, or an object with names and values. |
| `value` | `Object` | no | | The value to write. |
Returns: `Object` The value of the variable.
Variables are stored in [DEF.env](../def/). A text can refer to them as `[name]`: paths, addresses and configuration values replace this notation with the value. Pass an object to write several variables. Every write emits the `env` [event](../events/).
Example: Use a variable in a text
```js
ENV('api', '/api/v1/');
console.log(ENV('api')); // /api/v1/
console.log('[api]users/'.env()); // /api/v1/users/
```
### ENVIRONMENT(name, [version], [language], [env])
Type: `method`
Sets the storage key, version, language and environment variables of the app.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The key used in `localStorage`. |
| `version` | `String` | no | | The version of the app. |
| `language` | `String` | no | | The language of the app. |
| `env` | `Object` | no | | Environment variables. |
The method assigns [DEF.localstorage](../def/), [DEF.version](../def/) and [DEF.language](../def/), and passes `env` to [ENV()](../globals/). Call it directly after the library script, so that the app reads its own storage.
Example: Configure an app
```js
ENVIRONMENT('myapp', '1.0', 'en', { title: 'My app' });
console.log(DEF.localstorage, DEF.version, DEF.language); // myapp 1.0 en
console.log(ENV('title')); // My app
```
### ERROR(response, [success], [error])
Type: `method`
Checks a response for errors and runs the matching handler.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `response` | `Object` | yes | | The response to check. |
| `success` | `Function|String` | no | | Runs when there is no error. |
| `error` | `Function|String` | no | | Runs when there is an error. |
Returns: `Boolean` `true` when the response holds an error.
A response is an error when it is an `Error` object, has an `error` property, or is an array whose first item has one. An error emits the `ERROR` [event](../events/).
`success` and `error` can be functions, or names for [SEEX()](../globals/).
Call `ERROR(success, [error])` without a response to create a function that you can pass as a callback.
Example: Check a response
```js
console.log(ERROR({ id: 1 })); // false
console.log(ERROR([{ error: 'Invalid name' }])); // true
```
Example: Create a callback
```js
var callback = ERROR(function(response) {
console.log(response.id); // 1
});
callback({ id: 1 });
```
### ERRORS(path, callback)
Type: `method`
Returns the invalid components of a path or of an element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String|jQuery` | yes | | A path, or an element that contains the components. |
| `callback` | `Function` | yes | | A function that receives an array of [components](../component/). |
Example: Validate a form
```html
```
### EXEC(name, [a], [b], [c], [d])
Type: `method`
Calls a function by its name.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The target of the call. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
The form of `name` decides what is called:
| Name | Calls |
| --- | --- |
| `name` | A global function. |
| `FUNC.name` | A function found at a path. |
| `plugin/method` | A method of a [plugin](../plugin/). |
| `*/method` | A method of the common plugin. |
| `-component/method` | A component method, through [SETTER()](../globals/). |
| `#event` | An event, through [EMIT()](../globals/). |
Add the flag `@important` to retry every 500 milliseconds until the function exists, for example `EXEC('app/refresh @important')`. `EXE()` is the same function under another name.
Example: Call a function by path
```js
FUNC.sum = function(a, b) {
console.log(a + b); // 5
};
EXEC('FUNC.sum', 2, 3);
```
Example: Wait for a function
```js
EXEC('app.start @important', 'now');
setTimeout(function() {
window.app = {};
app.start = function(value) {
console.log(value); // now
};
}, 100);
```
### EXTENSION(name, [config], callback)
Type: `method`
Extends a component or a plugin.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The component name, or `@` followed by the plugin name. |
| `config` | `String|Object` | no | | Configuration added to each instance. |
| `callback` | `Function` | yes | | A function `(instance, config, cls)`, where `cls` is the CSS class of the instance. `this` is the instance. |
The `callback` runs for every existing instance and for every new one, right after the declaration, always with the same arguments. For a plugin, write `@` in front of its name.
Example: Add a method to a component
```html
```
### FIND(selector, [all])
Type: `method`
Finds a component that is ready.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `selector` | `String` | yes | | The name, the identifier or the path. |
| `all` | `Boolean` | no | `false` | Returns all the matches in an array. |
Returns: `Component|Array` The first [component](../component/), or an array when `all` is `true`.
The `selector` is a component name, `#id` for an identifier, or `.path` for a path.
Example: Find by name and by path
```html
```
### FLAGS(flags, [callback])
Type: `method`
Emits flags and then runs a function.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `flags` | `String` | yes | | The flags, for example `@loading @save`. |
| `callback` | `Function` | no | | A function that runs afterwards. |
Each flag emits the event `@flag name`, which you can capture with [ON()](../globals/). See [Flags and path modifiers](../../guides/flags/).
Example: Capture a flag
```js
ON('@flag loading', function() {
console.log('flag captured'); // flag captured
});
FLAGS('@loading', function() {
console.log('done'); // done
});
```
### FN(code)
Type: `method`
Compiles an arrow function from a string.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `String` | yes | | The code of the function. |
Returns: `Function` The compiled function.
The code can have up to four arguments. Code without an arrow becomes a function with the argument `value`. Compiled functions are cached.
Example: Compile functions
```js
console.log(FN('n => n * 2')(4)); // 8
console.log(FN('(a, b) => a + b')(1, 2)); // 3
console.log(FN('value + 1')(1)); // 2
```
### FREE()
Type: `method`
Removes components, bindings and plugins whose elements have left the DOM.
The library runs this cleanup every minute. Call it when you need the instances to be removed right away.
Example: Remove a detached component
```html
```
### FUNC
Type: `property`
An empty object for the functions of your app.
Returns: `Object` The container.
Functions stored here can be called by path with [EXEC()](../globals/).
Example: Store a function
```js
FUNC.hello = function() {
return 'Hello';
};
console.log(FUNC.hello()); // Hello
```
### GET(path, [noflags])
Type: `method`
Reads the value of a path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path, optionally with flags. |
| `noflags` | `Boolean` | no | `false` | Reads the value without applying the flags. |
Returns: `Object` The value.
When the path contains flags, they are applied to the components of the path: `GET('form @reset')` returns the value and resets their state. See [Paths](../../guides/paths/).
Example: Read values
```js
SET('user.name', 'Peter');
console.log(GET('user.name')); // Peter
console.log(GET('user')); // {"name":"Peter"}
```
### GUID([length])
Type: `method`
Generates a random identifier.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | no | | The length of the identifier. |
Returns: `String` The identifier.
Without `length`, the result has the 36-character form of a UUID. With `length`, it is a string of lowercase letters and digits.
Example: Generate identifiers
```js
console.log(GUID().length); // 36
console.log(GUID(10).length); // 10
```
### HASH(value)
Type: `method`
Creates a numeric hash of a value.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Number|Boolean|Object|Date` | yes | | The value. |
Returns: `Number` The hash.
A number is returned as it is, `true` gives `1`, a date gives its time in milliseconds, and an empty value gives `0`. Objects are serialized first.
Example: Hash a string
```js
console.log(HASH('hello')); // 99162322
```
### HIDDEN(element)
Type: `method`
Checks whether an element nested in the page is hidden.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery|Element` | yes | | An element placed inside another element of the body. |
Returns: `Boolean` `true` when the element is hidden.
The element counts as hidden when it has no offset parent, which is the case for `display:none`. A missing element also counts as hidden. To check the position in the viewport, use [VISIBLE()](../globals/).
Example: Check an element
```html
```
### IMPORT(url, [target], [callback], [prepare])
Type: `method`
Loads a script, a stylesheet or a piece of HTML.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes | | The address and optional keywords. |
| `target` | `String|jQuery|Element` | no | `body` | The element that receives HTML content. |
| `callback` | `Function` | no | | A function that runs when the content is loaded. |
| `prepare` | `Function` | no | | A function that receives the HTML and returns the text to insert. |
Addresses ending with `.js` or `.css` are added to the page head. Any other address is downloaded and inserted into `target`. Keywords can be combined with the address:
| Keyword | Meaning |
| --- | --- |
| `` | Skips the import when the global variable `name` exists. |
| `.js`, `.css`, `.html` | Sets the type of the content when the address does not show it. |
| `@singleton` | Imports the address only once. |
| `@prepend` | Inserts the content at the beginning of `target`. |
When a script or a stylesheet cannot be loaded, the library writes a warning to the console and `callback` still runs.
See [Importing content](../../guides/importing/).
Example: Insert a piece of HTML
```html
```
Example: Skip a library that exists
```js
IMPORT(' /js/jquery.min.js', function() {
console.log('jQuery is available'); // jQuery is available
});
```
### INC(path, [value])
Type: `method`
Increases the number stored in a path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path. |
| `value` | `Number` | no | `1` | The amount to add. |
An empty path starts at `0`. A string is converted to a number. Use a negative `value` to decrease the number.
Example: Increase a counter
```js
SET('stats.visits', 10);
INC('stats.visits');
INC('stats.visits', 5);
console.log(GET('stats.visits')); // 16
```
### inDOM(element)
Type: `method`
Checks whether an element is attached to the document body.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `Element` | yes | | A DOM element. |
Returns: `Boolean` `true` when the element is attached, otherwise nothing.
Example: Check an element
```js
console.log(inDOM(document.body)); // true
console.log(!!inDOM(document.createElement('div'))); // false
```
### isIE
Type: `property`
Tells whether the browser is Internet Explorer.
Returns: `Boolean` The result of the detection.
### isMOBILE
Type: `property`
Tells whether the user agent belongs to a mobile device.
Returns: `Boolean` The result of the detection.
### isPRIVATEMODE
Type: `property`
Tells whether `localStorage` is unavailable, as in some private windows. The value is set while the library starts, so read it from the `ready` event onward.
Returns: `Boolean` The result of the detection.
### isROBOT
Type: `property`
Tells whether the user agent belongs to a search engine or a crawler.
Returns: `Boolean` The result of the detection.
### isSTANDALONE
Type: `property`
Tells whether the page runs as an installed web app.
Returns: `Boolean` The result of the detection.
### isTOUCH
Type: `property`
Tells whether the device supports touch input.
Returns: `Boolean` The result of the detection.
### jComponent
Type: `property`
The main object of the library.
Returns: `Object` The main object.
The same object as [MAIN](../main/).
### LOCALIZE(text)
Type: `method`
Loads translations into the dictionary.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `text` | `String` | yes | | The lines with translations. |
Each line has the form `key : translation`, and lines starting with `//` are skipped. The key is the hash of the original text, in base 36, with the prefix `T`. The translations are stored in [DEF.dictionary](../def/) and used by [TRANSLATE()](../globals/). See [Localization](../../guides/localization/).
Example: Load a translation
```js
var key = 'T' + HASH('Hello').toString(36);
LOCALIZE(key + ' : Hola');
console.log(TRANSLATE('@(Hello)')); // Hola
```
### M
Type: `property`
A short name of the main object.
Returns: `Object` The main object.
The same object as [MAIN](../main/).
### MAIN
Type: `property`
The main object of the library.
Returns: `Object` The main object.
Described on its own page: [MAIN](../main/).
### MONTHS
Type: `property`
The English names of the months, starting with January.
Returns: `Array` Twelve strings.
Example: Read a month
```js
console.log(MONTHS[0]); // January
```
### NEWUIBIND(element, [path], [config])
Type: `method`
Creates a data binding on an element from code.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery|Element` | yes | | The element. |
| `path` | `String` | no | | The path to observe. |
| `config` | `String` | no | | The binding commands. |
The binding works like the [ui-bind](../ui-bind/) element. Without `path` and `config`, the values are read from the attributes of the element.
Example: Bind an element to a path
```html
```
### NODEINDEXOF(element)
Type: `method`
Returns the position of an element among its siblings.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery|Element` | yes | | The element. |
Returns: `Number` The zero-based position.
Example: Read a position
```html
```
### NODEINSERT(element, reference, [before])
Type: `method`
Inserts an element next to another element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery|Element` | yes | | The element to insert. |
| `reference` | `jQuery|Element` | yes | | The reference element. |
| `before` | `Boolean` | no | `false` | Inserts the element in front of the reference. |
Example: Move an element
```html
```
### NODEMOVE(element, [up])
Type: `method`
Moves an element one position among its siblings.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery|Element` | yes | | The element. |
| `up` | `Boolean` | no | `false` | Moves the element towards the start. Otherwise it moves towards the end. |
Example: Reorder a list
```html
```
### NOOP()
Type: `method`
A function that does nothing.
Use it as a default callback.
Example: A default callback
```js
var callback = NOOP;
console.log(typeof(callback)); // function
```
### NOTFOCUSED()
Type: `method`
Checks whether the page is in the background.
Returns: `Boolean` `true` when the document is hidden.
Example: Check the page
```js
console.log(NOTFOCUSED()); // false
```
### NOW
Type: `property`
The current date, refreshed once a minute.
Returns: `Date` The date.
Use it when a precision of one minute is enough. It avoids creating a new `Date` object for each use.
Example: Read the date
```js
console.log(NOW instanceof Date); // true
```
### NUL(path)
Type: `method`
Sets a path to `null`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path. |
`NULL()` is the same function under another name.
Example: Clear a value
```js
SET('user.name', 'Peter');
NUL('user.name');
console.log(GET('user.name')); // null
```
### OFF(name, [callback])
Type: `method`
Removes event handlers.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the event. |
| `callback` | `Function` | no | | The handler to remove. |
Without `callback`, all the handlers of the event are removed. Several events can be joined with `+`.
Example: Remove a handler
```js
var count = 0;
var handler = function() {
count++;
};
ON('refresh', handler);
EMIT('refresh');
OFF('refresh', handler);
EMIT('refresh');
console.log(count); // 1
```
### ON(name, callback, [init])
Type: `method`
Registers an event handler.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the event. |
| `callback` | `Function` | yes | | The handler. It receives the arguments of the event. |
| `init` | `Boolean` | no | `false` | Also calls the handler once, without arguments. |
Several events can be joined with `+`, for example `saved + removed`. A handler for `ready` or `init` runs immediately when the library has started. The events of the library are listed in [Events](../events/).
Example: Capture two events
```js
var count = 0;
ON('saved + removed', function() {
count++;
});
EMIT('saved');
EMIT('removed');
console.log(count); // 2
```
### PARSE(value)
Type: `method`
Parses JSON and converts date strings to `Date` objects.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Object` | yes | | The JSON, a selector or an object. |
Returns: `Object` The parsed value, or `null`.
A value starting with `#` or `.` is a selector: the JSON is read from the content of that element. An object is returned as it is. Invalid JSON returns `null`.
Example: Parse JSON
```js
var data = PARSE('{"created":"2024-05-01T10:00:00.000Z"}');
console.log(data.created instanceof Date); // true
console.log(PARSE('invalid')); // null
```
### PIPE(name, [data], callback, [scope])
Type: `method`
Calls an operation on the address from `DEF.pipe`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the operation, optionally followed by keywords. |
| `data` | `Object` | no | | The data of the operation. |
| `callback` | `Function|String` | yes | | A function or a path that receives the response. |
| `scope` | `Object` | no | `window` | The object in which a `callback` path is resolved. |
It works like [API()](../globals/), with the address taken from [DEF.pipe](../def/).
Example: Call an operation
```js
DEF.pipe = '/pipe/';
PIPE('orders_list', function(response) {
console.log(response.length); // 1
});
```
### PLUGIN(name, [config], callback, [dependencies])
Type: `method`
Registers a plugin declaration.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the plugin. |
| `config` | `String` | no | | The default configuration in the form `key:value;key:value`. |
| `callback` | `Function` | yes | | The declaration: `function(self, config)`. |
| `dependencies` | `String|Array` | no | | Addresses to import first. |
The `callback` runs when a [ui-plugin](../ui-plugin/) element with this path is created. The name `*` registers the common plugin. See [Plugins](../../guides/plugins/) and the [Plugin](../plugin/) object.
Example: Declare a plugin
```html
```
### PLUGINS
Type: `property`
The running plugin instances, by name.
Returns: `Object` The [plugin](../plugin/) instances.
Example: Read a plugin
```html
```
### PREF
Type: `property`
Persistent user preferences.
Returns: `Object` The preferences.
Described on its own page: [PREF](../pref/).
### PUSH(path, value)
Type: `method`
Adds an item to the array stored in a path and notifies the path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path of an existing array. |
| `value` | `Object` | yes | | The item. |
Write `^` in front of the path to add the item at the beginning of the array.
Example: Add items
```js
SET('tags', ['b']);
PUSH('tags', 'c');
PUSH('^tags', 'a');
console.log(GET('tags')); // ["a","b","c"]
```
### QUERIFY([url], data)
Type: `method`
Adds data to an address as a query string.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no | | The address. |
| `data` | `Object` | yes | | The values. |
Returns: `String` The address with the query string.
Empty values are skipped, dates are converted to ISO strings and arrays are joined with commas. The `url` can start with an HTTP method.
Example: Build addresses
```js
console.log(QUERIFY('/users/', { page: 2, q: 'a b' })); // /users/?page=2&q=a%20b
console.log(QUERIFY('GET /users/', { page: 2 })); // GET /users/?page=2
console.log(QUERIFY({ page: 2 })); // ?page=2
```
### REPO
Type: `property`
An empty object for the shared data of your app.
Returns: `Object` The container.
Example: Store a value
```js
REPO.title = 'My app';
console.log(REPO.title); // My app
```
### RESET(path)
Type: `method`
Resets the state of the components bound to a path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path. |
The `touched` and `modified` states return to their defaults. The value of the path does not change.
Example: Reset a form
```html
```
### SCROLLBAR(element, [options])
Type: `method`
Adds a custom scrollbar to an element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery` | yes | | The element. |
| `options` | `Object` | no | | The options. |
Returns: `Object` The scrollbar.
Options:
| Option | Type | Description |
| --- | --- | --- |
| `native` | Boolean | Keeps the scrollbar of the browser and only sets the overflow. |
| `orientation` | String | `x` or `y`. By default, both directions are active. |
| `visibleX`, `visibleY` | Boolean | Keeps the track visible when there is nothing to scroll. |
| `wrap` | Boolean | `false` uses the existing content as the scroll area. |
| `controls` | jQuery | The element that receives the scrollbar tracks. |
| `shadow` | Boolean | Adds shadows on the scrollable edges. |
| `padding` | Number | The distance of the tracks from the edge. Default `5`. |
| `minsize` | Number | The minimum size of the bar. Default `50`. |
| `thickness` | Number | The thickness used when CSS does not define it. Default `10`. |
| `margin`, `marginX`, `marginY` | Number | Adjust the size of the scroll area. |
| `offsetX`, `offsetY` | Number | Adjust the measured size of the element. |
| `floating` | Boolean | `false` reserves space for the bars. |
| `parent` | String\|jQuery | The element whose size is used. |
| `interval` | Number | The time between size checks, in milliseconds. Default `54321`. |
| `autoresize` | Boolean | `false` stops measuring the element again when the window is resized. Default `true`. |
| `onscroll`, `onidle`, `onresize` | Function | Handlers that receive the scrollbar. |
The returned object provides:
| Member | Description |
| --- | --- |
| `area` | The scrolling element. |
| `body` | The element with the content. |
| `element` | The original element. |
| `resize()` | Measures the element again. |
| `scrollTop([value])` | Reads or sets the vertical position. A string such as `'+20'` moves relative to the current position. |
| `scrollLeft([value])` | Reads or sets the horizontal position, with the same rules. |
| `scrollBottom(offset)` | Scrolls to the bottom, minus `offset`. |
| `scrollRight(offset)` | Scrolls to the right edge, minus `offset`. |
| `scroll(x, y)` | Scrolls to a position. |
| `sync(element, [direction])` | Synchronizes scrolling with another element. `direction` is `x` or `y`. |
| `destroy()` | Stops the scrollbar. |
The `scroll` and `scrollidle` [events](../events/) report scrolling.
Example: Scroll from code
```html
```
### SCROLLBARWIDTH()
Type: `method`
Returns the width of the scrollbar of the browser.
Returns: `Number` The width in pixels.
Example: Read the width
```js
console.log(typeof(SCROLLBARWIDTH())); // number
```
### SEEX(name, [a], [b], [c], [d])
Type: `method`
Calls a function or writes a value, depending on the name.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The target. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
The form `plugin/method` calls a plugin method, and the name of a global function calls that function. Any other name is a path, and `a` is written to it with [SET()](../globals/).
Example: Write to a path
```js
SEEX('form.name', 'Peter');
console.log(GET('form.name')); // Peter
```
Example: Call a global function
```js
window.notify = function(text) {
console.log(text); // Saved
};
SEEX('notify', 'Saved');
```
### SET(path, value)
Type: `method`
Writes a value to a path and notifies everything that observes it.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path, optionally with flags. |
| `value` | `Object` | yes | | The value, or a function `(current)` that returns it. |
Missing objects along the path are created. Flags are part of the path, for example `form.name @change`. The form `path[]` appends the value to an array. A function as `value` receives the current value, and its result is written. See [Paths](../../guides/paths/) and [Flags and path modifiers](../../guides/flags/).
Example: Write values
```js
SET('user.name', 'Peter');
SET('user.tags[]', 'admin');
console.log(GET('user')); // {"name":"Peter","tags":["admin"]}
```
Example: Write a value from the current one
```js
SET('cart.count', 1);
SET('cart.count', value => value + 1);
console.log(GET('cart.count')); // 2
```
### SETTER(name, [a], [b], [c], [d])
Type: `method`
Calls a method on the components that match a selector.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The selector and the method. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
The `name` has the form `selector/method`:
| Selector | Matches |
| --- | --- |
| `name` | Components with this name. |
| `#id` | The component with this identifier. |
| `*` | All components that have the method. |
The flag `@important` retries every 500 milliseconds until a matching component with the method exists. A component declared as lazy is created by the first call, unless the name starts with `!`.
Example: Call a component method
```html
```
### setTimeout2(name, callback, timeout, [limit], [param])
Type: `method`
Runs a function after a delay, restarting the delay on each call with the same name.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the timer. |
| `callback` | `Function` | yes | | The function. |
| `timeout` | `Number` | yes | | The delay in milliseconds. |
| `limit` | `Number` | no | | The maximum number of calls in one waiting period. |
| `param` | `Object` | no | | The argument of the function. |
Returns: `String` The name of the timer. A call ignored by `limit` returns nothing.
With `limit`, the delay is restarted at most `limit` times. Further calls are ignored until the function runs, so it cannot be postponed forever.
Example: Run once after the last call
```js
var count = 0;
var run = function() {
count++;
console.log(count); // 1
};
setTimeout2('search', run, 50);
setTimeout2('search', run, 50);
setTimeout2('search', run, 50);
```
### STRINGIFY(value, [compress], [fields], [encrypt])
Type: `method`
Serializes a value to JSON.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes | | The value. |
| `compress` | `Boolean` | no | `false` | Removes empty values. |
| `fields` | `Array|Object|Function` | no | | The keys to keep. |
| `encrypt` | `Boolean|String` | no | | `true` encodes the JSON with [ENCRYPT()](../globals/). A string does the same and is the key. |
Returns: `String` The JSON.
With `compress` set to `true`, strings are trimmed, and empty strings, `false` and `null` are left out. The `fields` argument selects the keys: an array of allowed keys, an object where `false` excludes a key, or a function `(key, value)` that returns `true` for the keys to keep.
Example: Compress and filter
```js
var data = { name: ' Peter ', note: '', age: 30 };
console.log(STRINGIFY(data, true)); // {"name":"Peter","age":30}
console.log(STRINGIFY(data, false, ['age'])); // {"age":30}
```
Example: Encode the JSON
```js
var text = STRINGIFY({ id: 5 }, false, null, 'secret');
console.log(DECRYPT(text, 'secret')); // {"id":5}
```
### STYLE(value, [id], [selector])
Type: `method`
Adds CSS to the page.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String|Array` | yes | | The CSS. |
| `id` | `String` | no | | The identifier of the style element. |
| `selector` | `String` | no | | A selector that prefixes every rule. |
An element with the same `id` is replaced. The element has the identifier `css` followed by `id`. With `selector`, every rule is prefixed with this selector.
Example: Add scoped styles
```js
STYLE('b { color: red }', 'theme', '.panel');
console.log($('#csstheme').html()); // .panel b{ color: red }
```
### TAPI(name, [data], callback, [scope])
Type: `method`
Calls a Total.js API operation on the address from `DEF.api`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the operation, optionally followed by keywords. |
| `data` | `Object` | no | | The data of the operation. |
| `callback` | `Function|String` | yes | | A function or a path that receives the response. |
| `scope` | `Object` | no | `window` | The object in which a `callback` path is resolved. |
It works like [API()](../globals/), with the address taken from [DEF.api](../def/).
Example: Store a response in a path
```js
DEF.api = '/admin/api/';
TAPI('users_list', { page: 1 }, 'users.items');
WATCH('users.items', function(value) {
console.log(value.length); // 2
});
```
### TEMP
Type: `property`
An object for short-lived data.
Returns: `Object` The container.
The library replaces it with an empty object every minute.
Example: Store a value
```js
TEMP.result = 5;
console.log(TEMP.result); // 5
```
### TOGGLE(path)
Type: `method`
Inverts the boolean value of a path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path. |
Example: Toggle a value
```js
SET('menu.open', false);
TOGGLE('menu.open');
console.log(GET('menu.open')); // true
```
### Total
Type: `property`
The main object of the library.
Returns: `Object` The main object.
The same object as [MAIN](../main/).
### TRANSLATE(text)
Type: `method`
Replaces the `@(text)` markup with translations.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `text` | `String` | yes | | The text with the markup. |
Returns: `String` The translated text.
Text without a translation stays in its original language. Translations are loaded with [LOCALIZE()](../globals/).
Example: Translate a text
```js
LOCALIZE('T' + HASH('Yes').toString(36) + ' : Ano');
console.log(TRANSLATE('@(Yes) / @(No)')); // Ano / No
```
### UNAUTHORIZED(...permissions)
Type: `method`
Checks the permissions of the signed-in user.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `permissions` | `String` | yes | | One or more permissions. |
Returns: `Boolean` `true` when access is denied.
The method reads the global variable `user`. A user with `sa` or `su` set has all the permissions. Otherwise, the permissions come from `user.permissions` or `user.roles`, as an array or an object. The result is `true` when the user has none of the given permissions, or when `user` does not exist.
Example: Check a permission
```js
window.user = { roles: ['editor'] };
console.log(UNAUTHORIZED('editor')); // false
console.log(UNAUTHORIZED('admin')); // true
```
### UNWATCH(path, [callback])
Type: `method`
Removes watchers from a path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path. Several paths can be joined with `+`. |
| `callback` | `Function` | no | | The watcher to remove. |
Without `callback`, all the watchers of the path are removed.
Example: Stop watching
```js
var count = 0;
var watcher = function() {
count++;
};
WATCH('form.name', watcher);
SET('form.name', 'A');
UNWATCH('form.name', watcher);
SET('form.name', 'B');
console.log(count); // 1
```
### UPD(path)
Type: `method`
Notifies a path after its value was changed directly.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path, optionally with flags. |
`UPDATE()` is the same function under another name.
Example: Notify after a direct change
```js
window.form = { name: 'A' };
WATCH('form.name', function(value) {
console.log(value); // B
});
form.name = 'B';
UPD('form.name');
```
### VISIBLE(element, [threshold], [mode])
Type: `method`
Checks the vertical position of an element relative to the viewport.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery|Element` | yes | | The element. |
| `threshold` | `Number` | no | `0` | The number of pixels of the element that must be inside the viewport. |
| `mode` | `String` | no | `visible` | `visible`, `above` or `below`. |
Returns: `Boolean` The result of the check.
The `mode` selects the check: `visible` tests whether the element is in the viewport, `above` whether it is above it, and `below` whether it is below it. A hidden element returns `false`.
Example: Check an element
```html
Top
Far
```
### W
Type: `property`
A short name of the `window` object.
Returns: `Object` The `window` object.
Example: Compare the objects
```js
console.log(W === window); // true
```
### WAIT(condition, callback)
Type: `method`
Runs a function when a condition is met.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `condition` | `Function|String` | yes | | A function or a path. |
| `callback` | `Function` | yes | | The function to run. |
The condition is checked immediately and then every 500 milliseconds. A function must return a truthy value. For a path, the wait ends when the path holds a truthy value.
Example: Wait for a value
```js
WAIT('app.config', function() {
console.log(GET('app.config.name')); // Demo
});
setTimeout(function() {
SET('app.config', { name: 'Demo' });
}, 100);
```
### WARN(...values)
Type: `method`
Prints a warning to the browser console.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `values` | `Object` | yes | | The values to print. |
### WATCH(path, callback, [init])
Type: `method`
Observes changes of a path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path. |
| `callback` | `Function` | yes | | A function that receives `(value, flags, path)`: the watched value, the flags and the changed path. |
| `init` | `Boolean` | no | `false` | Also calls the watcher once after the registration. |
A watcher runs when its own path changes, when a parent path changes, and when a path nested below it changes. Several paths can be joined with `+`.
Example: Observe a path
```js
WATCH('user.name', function(value, flags, path) {
console.log(value, path); // Peter user.name
});
SET('user.name', 'Peter');
```
### WH
Type: `property`
The height of the window in pixels.
Returns: `Number` The height.
The value is set while the library starts, and is refreshed when the window is resized.
Example: Read the height
```js
ON('ready', function() {
console.log(typeof(WH)); // number
});
```
### WIDTH([element])
Type: `method`
Returns the name of the device size for the width of an element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery` | no | `window` | The measured element. |
Returns: `String` The name of the size.
The sizes `xs`, `sm`, `md` and `lg` are defined in [DEF.devices](../def/).
Example: Measure an element
```html
```
### WW
Type: `property`
The width of the window in pixels.
Returns: `Number` The width.
The value is set while the library starts, and is refreshed when the window is resized.
Example: Read the width
```js
ON('ready', function() {
console.log(typeof(WW)); // number
});
```
---
title: DEF
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/def/
updated: 2026-11-18T13:58:14.460Z
---
# DEF
> The default settings of the library.
`DEF` holds the default settings of the library. Assign the values directly after the library script, so that they apply from the start. [Getting started](../../guides/getting-started/) shows where this code belongs.
## API
### DEF.api = undefined
Type: `config`
The address used by `TAPI()`.
Returns: `String` Default: `undefined`.
Assign it to use [TAPI()](../globals/).
Example: Set the endpoint
```js
DEF.api = '/admin/api/';
console.log(DEF.api); // /admin/api/
```
### DEF.baseurl = ''
Type: `config`
The prefix that `String.ROOT()` adds to relative addresses.
Returns: `String|Function` Default: `''`.
A function receives the address and returns the final address. [DEF.root](../def/) takes priority. See [String](../string/).
Example: Prefix an address
```js
DEF.baseurl = '/app';
console.log('/users/'.ROOT()); // /app/users/
```
### DEF.cdn = ''
Type: `config`
The value of the `~CDN~` keyword in imported content.
Returns: `String` Default: `''`.
The keyword is replaced by [ADAPT()](../globals/).
Example: Use the keyword
```js
DEF.cdn = 'https://cdn.example.com';
console.log(ADAPT(null, null, '~CDN~/logo.png')); // https://cdn.example.com/logo.png
```
### DEF.cl = {}
Type: `config`
The loaded code lists.
Returns: `Object` Default: `{}`.
The path prefix `#` points here, so `#countries` is `DEF.cl.countries`. See [CL()](../globals/).
Example: Read a list through its path
```js
SET('#colors', ['red']);
console.log(DEF.cl.colors); // ["red"]
```
### DEF.color = '#4285F4'
Type: `config`
The accent colour of the app.
Returns: `String` Default: `'#4285F4'`.
[APPEARANCE()](../globals/) updates it.
Example: Change the colour
```js
APPEARANCE({ color: '#FF0000' });
console.log(DEF.color); // #FF0000
```
### DEF.currencies = {}
Type: `config`
The formatters used by `Number.currency()`.
Returns: `Object` Default: `{}`.
Each key is a currency name and each value is a function that receives the number. See [Number](../number/).
Example: Define a currency
```js
DEF.currencies.eur = function(value) {
return value.format(2) + ' EUR';
};
console.log((10).currency('eur')); // 10.00 EUR
```
### DEF.currency = ''
Type: `config`
The default currency of `Number.currency()`.
Returns: `String` Default: `''`.
Example: Set the default currency
```js
DEF.currencies.usd = function(value) {
return '$' + value.format(2);
};
DEF.currency = 'usd';
console.log((5).currency()); // $5.00
```
### DEF.dateformat = 'yyyy-MM-dd'
Type: `config`
The default format of `Date.format()` and of date parsing.
Returns: `String` Default: `'yyyy-MM-dd'`.
See [Date](../date/).
Example: Change the format
```js
DEF.dateformat = 'dd.MM.yyyy';
console.log(new Date(2024, 0, 15).format()); // 15.01.2024
```
### DEF.dateformatutc = false
Type: `config`
Formats all dates in UTC.
Returns: `Boolean` Default: `false`.
It applies to `Date.format()`. See [Date](../date/).
Example: Format in UTC
```js
DEF.dateformatutc = true;
console.log(new Date(Date.UTC(2024, 0, 15, 12, 30)).format('HH:mm')); // 12:30
```
### DEF.decimalseparator = '.'
Type: `config`
The decimal separator of formatted numbers.
Returns: `String` Default: `'.'`.
It is used by `Number.format()` and when numbers are parsed. See [Number](../number/).
Example: Use a decimal comma
```js
DEF.decimalseparator = ',';
console.log((1.5).format(2)); // 1,50
```
### DEF.devices = { xs: { max: 768 }, sm: { min: 768, max: 992 }, md: { min: 992, max: 1200 }, lg: { min: 1200 } }
Type: `config`
The width ranges of the device sizes.
Returns: `Object` Default: `{ xs: { max: 768 }, sm: { min: 768, max: 992 }, md: { min: 992, max: 1200 }, lg: { min: 1200 } }`.
The ranges are used by [WIDTH()](../globals/) and by the `jc-xs`, `jc-sm`, `jc-md` and `jc-lg` body classes.
Example: Read a range
```js
console.log(DEF.devices.md); // {"min":992,"max":1200}
```
### DEF.dictionary = {}
Type: `config`
The translations loaded with `LOCALIZE()`.
Returns: `Object` Default: `{}`.
See [Localization](../../guides/localization/).
Example: Read the dictionary
```js
LOCALIZE('Tabc : Hola');
console.log(DEF.dictionary.Tabc); // Hola
```
### DEF.empty = '---'
Type: `config`
The text displayed for an empty value.
Returns: `String` Default: `'---'`.
It is used by the `empty` command of [ui-bind](../ui-bind/) and by the `empty` [Tangular helper](../tangular-helpers/).
Example: Read the text
```js
console.log(DEF.empty); // ---
```
### DEF.env = { ts: 'yyyy-MM-dd - HH:mm', date: 'yyyy-MM-dd', time: 'HH:mm' }
Type: `config`
The environment variables.
Returns: `Object` Default: `{ ts: 'yyyy-MM-dd - HH:mm', date: 'yyyy-MM-dd', time: 'HH:mm' }`.
Variables are managed with [ENV()](../globals/). The default values can be used as date formats, for example `[ts]`.
Example: Use a variable as a date format
```js
var date = new Date(2024, 0, 15, 8, 5);
console.log(date.format('[ts]')); // 2024-01-15 - 08:05
```
### DEF.fallback = 'https://cdn.componentator.com/j-{0}.html'
Type: `config`
The address from which unknown components are downloaded.
Returns: `String` Default: `'https://cdn.componentator.com/j-{0}.html'`.
The `{0}` keyword becomes the component name. The `source` attribute of [ui-component](../ui-component/) overrides it.
Example: Read the address
```js
console.log(DEF.fallback.format('input')); // https://cdn.componentator.com/j-input.html
```
### DEF.firstdayofweek = 1
Type: `config`
The first day of the week, for components that display a calendar.
Returns: `Number` Default: `1`.
The value `0` is Sunday and `1` is Monday. The library only stores it.
Example: Start the week on Sunday
```js
DEF.firstdayofweek = 0;
console.log(DAYS[DEF.firstdayofweek]); // Sunday
```
### DEF.headers = { 'X-Requested-With': 'XMLHttpRequest' }
Type: `config`
The headers added to every `AJAX()` request.
Returns: `Object` Default: `{ 'X-Requested-With': 'XMLHttpRequest' }`.
Example: Add a header
```js
DEF.headers['x-token'] = '123456';
console.log(DEF.headers['x-token']); // 123456
```
### DEF.iconprefix = 'ti ti-'
Type: `config`
The prefix added to icon names by `component.icon()`.
Returns: `String` Default: `'ti ti-'`.
A value that contains a space is used as it is. See [Component](../component/).
Example: Change the prefix
```html
```
### DEF.language = undefined
Type: `config`
The language added to the query string of every `AJAX()` request.
Returns: `String` Default: `undefined`.
The name of the parameter is in [DEF.languagekey](../def/). [ENVIRONMENT()](../globals/) can set this value.
Example: Set the language
```js
DEF.language = 'en';
console.log(DEF.language); // en
```
### DEF.languagekey = 'language'
Type: `config`
The name of the query parameter that carries the language.
Returns: `String` Default: `'language'`.
Example: Read the name
```js
console.log(DEF.languagekey); // language
```
### DEF.localstorage = 'jc'
Type: `config`
The `localStorage` key of the cache.
Returns: `String` Default: `'jc'`.
[ENVIRONMENT()](../globals/) can set this value.
Example: Read the key
```js
console.log(DEF.localstorage); // jc
```
### DEF.onstorageread = function(callback)
Type: `config`
Loads the persistent cache when the library starts.
Returns: `Function` Default: `function(callback)`.
Assign your own function directly after the library script. It must call `callback` with the stored object. The default function reads `localStorage`.
Example: Provide the stored data
```js
DEF.onstorageread = function(callback) {
callback({});
};
ON('ready', function() {
console.log('loaded'); // loaded
});
```
### DEF.onstoragesave = function(data)
Type: `config`
Saves the persistent cache.
Returns: `Function` Default: `function(data)`.
The function receives an object with all the items that have an expiration. The default function writes to `localStorage`.
Example: Observe saving
```js
DEF.onstoragesave = function(data) {
console.log(Object.keys(data).length); // 1
};
ON('ready', function() {
CACHE('filter', 1, '1 day');
});
```
### DEF.path = { common: 'common.', cl: 'DEF.cl.', plugins: 'jComponent.data.', tmp: 'DEF.tmp.' }
Type: `config`
The targets of the short path prefixes.
Returns: `Object` Default: `{ common: 'common.', cl: 'DEF.cl.', plugins: 'jComponent.data.', tmp: 'DEF.tmp.' }`.
`common` is the target of `*`, `cl` of `#` and `tmp` of `%`. `plugins` holds the data of plugins with a generated path. The function `DEF.path.clean(name)` returns a value without the final dot. See [Paths](../../guides/paths/).
Example: Read a prefix
```js
console.log(DEF.path.common); // common.
console.log(DEF.path.clean('common')); // common
```
### DEF.pipe = undefined
Type: `config`
The address used by `PIPE()`.
Returns: `String` Default: `undefined`.
Assign it to use [PIPE()](../globals/).
Example: Set the endpoint
```js
DEF.pipe = '/pipe/';
console.log(DEF.pipe); // /pipe/
```
### DEF.prefixcsscomponents = 'ui-'
Type: `config`
The prefix of the CSS class that a component receives as `cls`.
Returns: `String` Default: `'ui-'`.
Example: Change the prefix
```html
```
### DEF.prefixcsslibrary = 'ui-'
Type: `config`
The prefix of the CSS classes created by the library.
Returns: `String` Default: `'ui-'`.
It is used by [APPEARANCE()](../globals/) and [SCROLLBAR()](../globals/).
Example: Change the prefix
```js
DEF.prefixcsslibrary = 'app-';
APPEARANCE({ dark: true });
console.log($('body').hclass('app-dark')); // true
```
### DEF.regexp = { int, float, date, pluralize, format, url, phone, email }
Type: `config`
The regular expressions used by the helpers.
Returns: `Object` Default: `{ int, float, date, pluralize, format, url, phone, email }`.
For example, `String.isEmail()` uses `DEF.regexp.email`. See [String](../string/).
Example: Validate an e-mail address
```js
console.log(DEF.regexp.email.test('info@example.com')); // true
console.log('invalid'.isEmail()); // false
```
### DEF.root = ''
Type: `config`
The prefix that `String.ROOT()` adds to every relative address.
Returns: `String|Function` Default: `''`.
It takes priority over [DEF.baseurl](../def/), and `ROOT(true)` applies only this value. See [String](../string/).
Example: Prefix an address
```js
DEF.root = '/admin';
console.log('/users/'.ROOT()); // /admin/users/
```
### DEF.scrollbaranimate = true
Type: `config`
Animates the bar of a custom scrollbar at the edges of the scrolling area.
Returns: `Boolean` Default: `true`.
See [SCROLLBAR()](../globals/).
Example: Disable the animation
```js
DEF.scrollbaranimate = false;
console.log(DEF.scrollbaranimate); // false
```
### DEF.thousandsseparator = ' '
Type: `config`
The thousands separator of formatted numbers.
Returns: `String` Default: `' '`.
It is used by `Number.format()` and when numbers are parsed. See [Number](../number/).
Example: Use a comma
```js
DEF.thousandsseparator = ',';
console.log((1234567).format(0)); // 1,234,567
```
### DEF.timeformat = 'HH:mm'
Type: `config`
The time format copied into the environment variables at startup.
Returns: `String` Default: `'HH:mm'`.
To change the format later, write the variables `time` and `ts` with [ENV()](../globals/).
Example: Read the format
```js
console.log(DEF.timeformat); // HH:mm
console.log(ENV('time')); // HH:mm
```
### DEF.tmp = {}
Type: `config`
The storage of temporary paths.
Returns: `Object` Default: `{}`.
The path prefix `%` points here, so `%form` is `DEF.tmp.form`. See [Paths](../../guides/paths/).
Example: Write a temporary value
```js
SET('%search', 'phone');
console.log(DEF.tmp.search); // phone
```
### DEF.version = undefined
Type: `config`
The version added to `.html` addresses requested with `AJAX()`.
Returns: `String` Default: `undefined`.
The name of the parameter is in [DEF.versionkey](../def/). [ENVIRONMENT()](../globals/) can set this value.
Example: Set the version
```js
DEF.version = '1.0';
console.log(DEF.version); // 1.0
```
### DEF.versionhtml = undefined
Type: `config`
The version for `.html` addresses when `DEF.version` is empty.
Returns: `String` Default: `undefined`.
Example: Set the version of HTML files
```js
DEF.versionhtml = '2';
console.log(DEF.versionhtml); // 2
```
### DEF.versionkey = 'version'
Type: `config`
The name of the query parameter that carries the version.
Returns: `String` Default: `'version'`.
Example: Read the name
```js
console.log(DEF.versionkey); // version
```
### DEF.warnings = false
Type: `config`
Prints the warnings of the library to the console.
Returns: `Boolean` Default: `false`.
Enable it during development, for example to report a method that was not found.
Example: Enable warnings
```js
DEF.warnings = true;
console.log(DEF.warnings); // true
```
---
title: MAIN
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/main/
updated: 2026-11-18T13:58:14.460Z
---
# MAIN
> The main object of the library, with its state and its low-level methods.
`MAIN` is the main object of the library. `M`, `Total` and `jComponent` are other names for the same object. It holds the state of the library and low-level methods that work with any scope. For everyday code, use the [global functions](../globals/) described with [Paths](../../guides/paths/).
## API
### MAIN.Binder
Type: `class`
The class of data bindings.
See [ui-bind](../ui-bind/).
### MAIN.binders
Type: `property`
The active data bindings.
Returns: `Array` The active data bindings.
See [ui-bind](../ui-bind/).
### MAIN.caller
Type: `property`
The plugin that was last called through `EXEC()`.
Returns: `Plugin` The plugin that was last called through `EXEC()`.
Example: Read the caller
```html
```
### MAIN.cl(name, [callback])
Type: `method`
The same function as `CL()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The names of the code lists. |
| `callback` | `Function` | no | | A function that runs when the lists are loaded. |
See [CL()](../globals/).
### MAIN.Component
Type: `class`
The class of components.
See [Component](../component/).
### MAIN.components
Type: `property`
The active component instances.
Returns: `Array` The active component instances.
See [Component](../component/).
Example: Count the components
```html
```
### MAIN.data
Type: `property`
The storage of plugins with a generated path.
Returns: `Object` The storage of plugins with a generated path.
See [DEF.path](../def/).
### MAIN.def
Type: `property`
The same object as `DEF`.
Returns: `Object` The same object as `DEF`.
See [DEF](../def/).
Example: Compare the objects
```js
console.log(MAIN.def === DEF); // true
```
### MAIN.emit(name, [a], [b], [c], [d])
Type: `method`
The same function as `EMIT()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the event. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
See [EMIT()](../globals/).
### MAIN.events
Type: `property`
The global event handlers, by event name.
Returns: `Object` The global event handlers, by event name.
See [Events](../events/).
### MAIN.exec(name, [a], [b], [c], [d])
Type: `method`
Runs the same logic as `EXEC()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The target of the call. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
See [EXEC()](../globals/).
### MAIN.find(scope, path, callback)
Type: `method`
Finds the components of a path in a scope.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `scope` | `Object` | yes | | The scope, usually `window`. |
| `path` | `String` | yes | | The path, optionally with flags. |
| `callback` | `Function` | yes | | A function that receives the array of components. |
Flags in the path narrow the result: `@visible`, `@touched`, `@modified`, `@required`, `@invalid`, `@disabled` and `@enabled`.
Example: Find components
```html
```
### MAIN.flags(flags, [callback])
Type: `method`
The same function as `FLAGS()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `flags` | `String` | yes | | The flags. |
| `callback` | `Function` | no | | A function that runs afterwards. |
See [FLAGS()](../globals/).
### MAIN.free()
Type: `method`
The same function as `FREE()`.
See [FREE()](../globals/).
### MAIN.get(scope, path)
Type: `method`
Reads a value from any object by a path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `scope` | `Object` | yes | | The object to read from. |
| `path` | `String` | yes | | The path inside the object. |
Returns: `Object` The value.
Example: Read a nested value
```js
var data = { user: { name: 'Peter' } };
console.log(MAIN.get(data, 'user.name')); // Peter
```
### MAIN.is20
Type: `property`
Identifies the major version of the library.
Returns: `Boolean` Identifies the major version of the library.
The value is always `true`.
Example: Read the value
```js
console.log(MAIN.is20); // true
```
### MAIN.loaded
Type: `property`
Becomes `true` when the persistent cache is loaded.
Returns: `Boolean` Becomes `true` when the persistent cache is loaded.
### MAIN.newbinder(element, path, config, [callback])
Type: `method`
Creates a data binding on an element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery` | yes | | The element. |
| `path` | `String` | yes | | The path. |
| `config` | `String` | yes | | The binding commands. |
| `callback` | `Function` | no | | A function that runs when the binding is created. |
See [NEWUIBIND()](../globals/).
### MAIN.newcomponent(element, name, path, config, [callback])
Type: `method`
Creates a component on an element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery` | yes | | The element. |
| `name` | `String` | yes | | The name of the component. |
| `path` | `String` | yes | | The path. |
| `config` | `String` | yes | | The configuration. |
| `callback` | `Function` | no | | A function that runs when the component is created. |
Example: Create a component from code
```html
```
### MAIN.newimporter(element, path, config)
Type: `method`
Imports content into an element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery` | yes | | The element. |
| `path` | `String` | yes | | The address. |
| `config` | `String` | yes | | The configuration of the import. |
It works like the [ui-import](../ui-import/) element.
Example: Import a part
```html
```
### MAIN.newplugin(element, path, config, [callback])
Type: `method`
Creates a plugin on an element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery` | yes | | The element. |
| `path` | `String` | yes | | The name of the plugin. |
| `config` | `String` | no | | The configuration. |
| `callback` | `Function` | no | | A function that runs when the plugin is created. |
Example: Create a plugin from code
```html
```
### MAIN.notify(scope, path, [onlyflags])
Type: `method`
Notifies the observers of a path in a scope.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `scope` | `Object` | yes | | The scope, usually `window`. |
| `path` | `String` | yes | | The path, optionally with flags. |
| `onlyflags` | `Boolean` | no | `false` | Limits the notification to the state of components. |
With `onlyflags`, components only refresh their state, and watchers do not run.
Example: Notify a path
```js
WATCH('total', function(value) {
console.log(value); // 5
});
window.total = 5;
MAIN.notify(window, 'total');
```
### MAIN.off(name, [callback])
Type: `method`
The same function as `OFF()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the event. |
| `callback` | `Function` | no | | The handler to remove. |
See [OFF()](../globals/).
### MAIN.on(name, callback, [init])
Type: `method`
The same function as `ON()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the event. |
| `callback` | `Function` | yes | | The handler. |
| `init` | `Boolean` | no | `false` | Also calls the handler once. |
See [ON()](../globals/).
### MAIN.parse(type, value, [format])
Type: `method`
Converts a value to a type.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes | | The type. |
| `value` | `Object` | yes | | The value. |
| `format` | `String` | no | | The format of a date. |
Returns: `Object` The converted value.
The types are `number`, `currency`, `float`, `boolean`, `bool`, `date` and `datetime`. Numbers follow [DEF.thousandsseparator](../def/) and [DEF.decimalseparator](../def/), and dates use [DEF.dateformat](../def/) when `format` is not set. A value that cannot be converted returns `null`. Other types return the value as it is.
Example: Convert values
```js
console.log(MAIN.parse('number', '1 200.5')); // 1200.5
console.log(MAIN.parse('boolean', 'yes')); // true
console.log(MAIN.parse('date', '2024-03-01') instanceof Date); // true
```
### new MAIN.Path(path)
Type: `class`
The class that parses paths.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path, optionally with flags. |
See [Path](../path/).
Example: Parse a path
```js
var path = new MAIN.Path('form.name @change');
console.log(path.path); // form.name
console.log(path.flags); // {"change":1}
```
### MAIN.Plugin
Type: `class`
The class of plugins.
See [Plugin](../plugin/).
### MAIN.plugins
Type: `property`
The same object as `PLUGINS`.
Returns: `Object` The same object as `PLUGINS`.
See [PLUGINS](../globals/).
### MAIN.process(scope, value, target)
Type: `method`
Delivers a value to a function or a path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `scope` | `Object` | yes | | The scope of a path. |
| `value` | `Object` | yes | | The value. |
| `target` | `Function|String` | yes | | A function or a path. |
A function receives the value. A path is written and notified in the scope.
Example: Deliver a value to a path
```js
MAIN.process(window, 5, 'stats.total');
console.log(GET('stats.total')); // 5
```
### MAIN.ready
Type: `property`
Becomes `true` when the library has started.
Returns: `Boolean` Becomes `true` when the library has started.
Example: Check the state
```js
ON('ready', function() {
console.log(MAIN.ready); // true
});
```
### MAIN.resize()
Type: `method`
Measures the window again.
The method updates [WW](../globals/) and [WH](../globals/). When the size has changed, it updates the device class on the body and emits the `resize2` [event](../events/).
### MAIN.root
Type: `property`
The `window` object, which is the scope of global paths.
Returns: `Object` The `window` object, which is the scope of global paths.
Example: Compare the objects
```js
console.log(MAIN.root === window); // true
```
### MAIN.scrollbars
Type: `property`
The active custom scrollbars.
Returns: `Array` The active custom scrollbars.
See [SCROLLBAR()](../globals/).
### MAIN.seex(name, [a], [b], [c], [d])
Type: `method`
Runs the same logic as `SEEX()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The target. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
See [SEEX()](../globals/).
### MAIN.set(scope, path, value)
Type: `method`
Writes a value to any object by a path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `scope` | `Object` | yes | | The object to write to. |
| `path` | `String` | yes | | The path inside the object. |
| `value` | `Object` | yes | | The value. |
Missing objects along the path are created. Nothing is notified.
Example: Write a nested value
```js
var data = {};
MAIN.set(data, 'user.name', 'Peter');
console.log(data); // {"user":{"name":"Peter"}}
```
### MAIN.setter(element, name, [a], [b], [c], [d])
Type: `method`
Runs `SETTER()` for the components inside an element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `element` | `jQuery|Plugin` | yes | | The element or the plugin that limits the search. |
| `name` | `String` | yes | | The selector and the method. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
Use `null` for all components. See [SETTER()](../globals/).
Example: Limit a call to an element
```html
```
### MAIN.ua
Type: `property`
The detected environment: `os`, `browser` and `device`.
Returns: `Object` The detected environment: `os`, `browser` and `device`.
The `device` is `desktop`, `tablet`, `mobile` or `tv`. The value is available from the `ready` event onward.
Example: Read the device
```js
ON('ready', function() {
console.log(Object.keys(MAIN.ua)); // ["os","browser","device"]
});
```
### MAIN.unwatch(path, [callback])
Type: `method`
The same function as `UNWATCH()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path. |
| `callback` | `Function` | no | | The watcher to remove. |
See [UNWATCH()](../globals/).
### MAIN.version
Type: `property`
The version of the library.
Returns: `Number` The version of the library.
Example: Read the version
```js
console.log(MAIN.version); // 20.015
```
### MAIN.watch(path, callback, [init])
Type: `method`
The same function as `WATCH()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path. |
| `callback` | `Function` | yes | | The watcher. |
| `init` | `Boolean` | no | `false` | Also calls the watcher once. |
See [WATCH()](../globals/).
### MAIN.watchers
Type: `property`
The watchers registered with `WATCH()`.
Returns: `Array` The watchers registered with `WATCH()`.
See [WATCH()](../globals/).
---
title: PREF
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/pref/
updated: 2026-11-18T13:58:14.460Z
---
# PREF
> Persistent user preferences.
`PREF` keeps user preferences, such as a theme or a language, between visits. The values are saved in the persistent cache described in [CACHE()](../globals/). The stored values are available from the `ready` [event](../events/) onward.
## API
### PREF.get(key)
Type: `method`
Reads a preference.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes | | The name of the preference. |
Returns: `Object` The value.
Example: Read a preference
```js
ON('ready', function() {
PREF.set('theme', 'dark');
console.log(PREF.get('theme')); // dark
});
```
### PREF.set(key, value)
Type: `method`
Writes a preference and saves all preferences for one year.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes | | The name of the preference. |
| `value` | `Object` | yes | | The value. |
Returns: `Object` The written value.
Write preferences from the `ready` [event](../events/) onward, when the stored values are loaded. The key `set` is reserved and is ignored.
Example: Write a preference
```js
ON('ready', function() {
console.log(PREF.set('language', 'en')); // en
console.log(PREF.language); // en
});
```
### PREF.{key}
Type: `property`
Each stored preference is also a property of the object.
Returns: `Object` The value of the preference.
Stored values are restored when the library starts. Reading a property is equal to calling [PREF.get()](../pref/). To save a change, use [PREF.set()](../pref/).
Example: Restore a stored value
```js
DEF.onstorageread = function(callback) {
var stored = {};
stored['ui' + HASH('PREF').toString(36)] = { value: { theme: 'dark' }, expire: new Date(Date.now() + 60000) };
callback(stored);
};
ON('ready', function() {
console.log(PREF.theme); // dark
});
```
---
title: Events
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/events/
updated: 2026-11-18T13:58:14.460Z
---
# Events
> The events emitted by the library.
The library emits these events. Capture them with [ON()](../globals/) and emit your own with [EMIT()](../globals/). [Components](../component/) and [plugins](../plugin/) can capture the same events with their own `on()` method.
## API
### ON('@flag name', function(path) {})
Type: `event`
Runs when a flag is used in a path, a call or `FLAGS()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path that carries the flag. It is empty when there is none. |
Replace `name` with the name of the flag. See [Flags and path modifiers](../../guides/flags/).
Example: Show a loading indicator
```js
ON('@flag loading', function() {
console.log('loading'); // loading
});
SET('form.name @loading', 'Peter');
```
### ON('bind', function(binder) {})
Type: `event`
Runs when a data binding is created.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `binder` | `Object` | yes | | The binding. |
See [ui-bind](../ui-bind/).
Example: Count the bindings
```html
```
### ON('component', function(component) {})
Type: `event`
Runs when a component is created.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `component` | `Component` | yes | | The instance. |
See [Component](../component/).
Example: Log the created components
```html
```
### ON('env', function(name, value) {})
Type: `event`
Runs when `ENV()` writes a variable.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the variable. |
| `value` | `Object` | yes | | The new value. |
A handler that writes one variable sees the new value in its arguments.
Example: Observe a variable
```js
ON('env', function(name, value) {
console.log(name, value); // title Demo
});
ENV('title', 'Demo');
```
### ON('ERROR', function(response) {})
Type: `event`
Runs when a response holds an error.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `response` | `Object|String` | yes | | The response or the status. |
The event is emitted by [ERROR()](../globals/) and by [AJAX()](../globals/) with the `ERROR` keyword. For a failed request without a body, the argument is the HTTP status as a string.
Example: Handle errors in one place
```js
ON('ERROR', function(response) {
console.log(response[0].error); // Invalid name
});
ERROR([{ error: 'Invalid name' }]);
```
Example: A failed request
```js
ON('ERROR', function(status) {
console.log(status); // 500
});
AJAX('GET /api/fail/ ERROR', NOOP);
```
### ON('import', function(url, target) {})
Type: `event`
Runs when `IMPORT()` has loaded content.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes | | The address. |
| `target` | `jQuery|String` | yes | | The script or link element, or the target of HTML content. |
Example: Observe imports
```html
```
### ON('init', function() {})
Type: `event`
Runs first while the library starts.
The persistent cache is not loaded yet. A handler registered after the start runs immediately.
Example: Prepare the app
```js
ON('init', function() {
console.log(MAIN.ready); // false
});
```
### ON('knockknock', function(counter) {})
Type: `event`
Runs every minute.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `counter` | `Number` | yes | | The number of minutes from the start of the page. |
It runs right after the `service` event.
Example: Run a periodic task
```js
ON('knockknock', function(counter) {
console.log(counter); // 1
});
```
### ON('plugin', function(plugin) {})
Type: `event`
Runs when a plugin is created.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `plugin` | `Plugin` | yes | | The instance. |
See [Plugin](../plugin/).
Example: Log the created plugins
```html
```
### ON('ready', function() {})
Type: `event`
Runs when the library and the components on the page are ready.
A handler registered after that moment runs immediately.
Example: Start the app
```html
```
### ON('request', function(options) {})
Type: `event`
Runs for every `AJAX()` call, ahead of sending the request.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | yes | | The request: `id`, `method`, `url`, `headers`, `data`, `scope`, `cancel`, `respond()` and, once the request is sent, `xhr`. |
The handler can change `options.url`, `options.method`, `options.headers` and `options.data`. Set `options.cancel = true` to stop the request. In that case, the callback does not run. Call `options.respond(value)` to answer the call without sending a request: the callback receives `value`. Once the request is sent, `options.xhr` holds its `XMLHttpRequest`.
Example: Add a token to each request
```js
ON('request', function(options) {
options.headers['x-token'] = '123';
console.log(options.method, options.url); // GET /api/users/
});
AJAX('GET /api/users/', NOOP);
```
Example: Answer without a request
```js
ON('request', function(options) {
if (options.url === '/api/config/')
options.respond({ theme: 'dark' });
});
AJAX('GET /api/config/', function(response) {
console.log(response.theme); // dark
});
```
### ON('resize2', function() {})
Type: `event`
Runs when the size of the window has changed.
The values of [WW](../globals/) and [WH](../globals/) are already updated.
Example: React to a new size
```js
ON('resize2', function() {
console.log(typeof(WW)); // number
});
```
### ON('response', function(options) {})
Type: `event`
Runs for every `AJAX()` response, ahead of the callback.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `options` | `Object` | yes | | The request together with `status`, `text`, `response`, `iserror`, `duration` and `headers`. |
The handler can change `options.response`. Set `options.cancel = true` to skip the callback.
Example: Log the responses
```js
ON('response', function(options) {
console.log(options.status, options.iserror); // 200 false
});
AJAX('GET /api/users/', NOOP);
```
### ON('scroll', function(area) {})
Type: `event`
Runs when scrolling starts in a custom scrollbar.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `area` | `jQuery` | yes | | The scrolling element. |
See [SCROLLBAR()](../globals/).
Example: Detect scrolling
```html
```
### ON('scrollidle', function(area) {})
Type: `event`
Runs when scrolling in a custom scrollbar has stopped.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `area` | `jQuery` | yes | | The scrolling element. |
The event comes 700 milliseconds after the last movement.
Example: Detect the end of scrolling
```html
```
### ON('service', function(counter) {})
Type: `event`
Runs every minute.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `counter` | `Number` | yes | | The number of minutes from the start of the page. |
The library refreshes [NOW](../globals/), removes expired cache items and clears [TEMP](../globals/) first.
Example: Run a periodic task
```js
ON('service', function(counter) {
console.log(counter); // 1
});
```
### ON('visible', function(visible) {})
Type: `event`
Runs when the page moves to the background or returns from it.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `visible` | `Boolean` | yes | | `true` when the page is visible. |
Example: Pause work in the background
```js
ON('visible', function(visible) {
console.log(visible); // true
});
```
---
title: Path
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/path/
updated: 2026-11-18T13:58:14.460Z
---
# Path
> The properties and the methods of a parsed path.
A Path object holds a parsed path with its flags. It is available as `component.path` and `plugin.path`, and `new jComponent.Path(path)` creates one. The syntax of paths is explained in [Paths](../../guides/paths/) and [Flags and path modifiers](../../guides/flags/).
## API
### path
Type: `property`
The clean path without flags.
Returns: `String` The clean path without flags.
Example: Parse a path
```js
var path = new jComponent.Path('form.user.name @touched #countries');
console.log(path.path);
// logs: form.user.name
console.log(JSON.stringify(path.flags));
// logs: {"touched":1}
console.log(path.cl);
// logs: countries
```
### raw
Type: `property`
The path with its flags, without code lists.
Returns: `String` The path with its flags, without code lists.
### flags
Type: `property`
The flags of the path as an object.
Returns: `Object` The flags of the path as an object.
A flag without a value has the value `1`. The form `@key:value` keeps the value.
### split
Type: `property`
The path divided into its levels, from the first to the whole path.
Returns: `Array` The path divided into its levels, from the first to the whole path.
### cl
Type: `property`
The names of the code lists written with `#`, separated with a comma.
Returns: `String` The names of the code lists written with `#`, separated with a comma.
### cache
Type: `property`
The text written between `<` and `>`.
Returns: `String` The text written between `<` and `>`.
### ERROR
Type: `property`
Is `true` when the path contains the keyword `ERROR`.
Returns: `Boolean` Is `true` when the path contains the keyword `ERROR`.
### SYNC
Type: `property`
Is `true` when the path contains the keyword `SYNC`.
Returns: `Boolean` Is `true` when the path contains the keyword `SYNC`.
### toString()
Type: `method`
Returns the clean path.
Returns: `String` The path.
Example: Convert to a string
```js
var path = new jComponent.Path('form.name @touched');
console.log(path.toString());
// logs: form.name
```
### get(scope)
Type: `method`
Reads the value at the path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `scope` | `Object` | yes | | The object that the path is resolved against, usually `window`. |
Returns: `Object` The value.
Example: Read and write in your own object
```js
var path = new jComponent.Path('user.name');
var scope = {};
path.set(scope, 'Anna');
console.log(JSON.stringify(scope), path.get(scope));
// logs: {"user":{"name":"Anna"}} Anna
```
### set(scope, value)
Type: `method`
Writes a value at the path, without notifying anything.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `scope` | `Object` | yes | | The object that the path is resolved against, usually `window`. |
| `value` | `Object` | yes | | The value to write. |
Missing parent objects are created.
### notify(scope, [flags])
Type: `method`
Notifies the components, watchers and binders bound to the path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `scope` | `Object` | yes | | The object that the path is resolved against, usually `window`. |
| `flags` | `String` | no | | Flags as a string such as `@touched`, or as an object such as `{ touched: 1 }`. |
Example: Notify the watchers
```js
var path = new jComponent.Path('common.count');
WATCH('common.count', (value, flags) => console.log(value, JSON.stringify(flags)));
path.set(window, 5);
path.notify(window, '@touched');
// logs: 5 {"touched":1}
```
### assign(path)
Type: `method`
Creates a path relative to this one.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The relative path. |
Returns: `Path` The new path.
The result depends on the first character of the argument:
| Argument | Result for `form.user` |
| --- | --- |
| `name` | `form.user.name` |
| `@touched` | `form.user` with the flag |
| `?suffix` | `form.usersuffix` |
| `*name` | `common.name` |
| `#name` | `DEF.cl.name` |
| `%name` | `DEF.tmp.name` |
Without an argument, the method returns the same object.
Example: Build relative paths
```js
var path = new jComponent.Path('form.user');
console.log(path.assign('name').path);
// logs: form.user.name
console.log(path.assign('*name').path);
// logs: common.name
```
### includes(path, [partially])
Type: `method`
Tells whether two paths lie on the same branch.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path to compare. |
| `partially` | `Boolean` | no | `false` | Compares the last level of the argument. |
Returns: `Boolean` The result of the comparison.
The result is `true` when one path is a parent of the other or both are the same. With `partially`, it is also `true` when a level of this path ends with the last level of the argument.
Example: Compare paths
```js
var path = new jComponent.Path('form.user');
console.log(path.includes('form'), path.includes('form.user.name'), path.includes('form.other'));
// logs: true true false
console.log(new jComponent.Path('form.user.name').includes('name', true));
// logs: true
```
### exec(callback)
Type: `method`
Emits the flags of the path, loads its code lists and calls a function.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes | | The function to call. |
Each flag is emitted as the event `@flag name`, with the path as the argument.
Example: Run the flags of a path
```js
ON('@flag saved', path => console.log('flag', path));
new jComponent.Path('form.user @saved').exec(() => console.log('done'));
// logs: flag form.user
// logs: done
```
### find(scope, callback)
Type: `method`
Finds the ready components bound to the path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `scope` | `Object` | yes | | The object that the path is resolved against, usually `window`. |
| `callback` | `Function` | yes | | A function `(components)`. |
The flags `@visible`, `@touched`, `@modified`, `@required`, `@invalid`, `@disabled` and `@enabled` limit the result.
Example: Find components in a form
```html
```
---
title: ui-bind
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/ui-bind/
updated: 2026-11-22T18:42:02.302Z
---
# ui-bind
> The attributes and the commands of the ui-bind element.
The `` element updates the page each time the value at a path changes. The `config` attribute holds a list of commands separated with `;`. The [Data binding](../../guides/data-binding/) guide explains how to use it.
A command has the form `name:expression`, or `name selector:expression` to act on the elements found by a selector inside the target. Without an expression, the command uses the value at the path. The expression is JavaScript and can use `value`, `path`, `flags`, `element` and `el` (the same as `element`). Join command names with `+` to give them the same expression, for example `text+title:value`. Write `\\;` for a semicolon inside an expression. All commands run once when the element is created, with the current value at the path. An error in an expression is written to the console and the commands continue.
## API
### path="path"
Type: `property`
The path to observe.
A `?` is replaced with the path of the parent plugin. With a `!` at the beginning (`!common.user`), the commands do not run while the value is `null` or `undefined`.
Example: Skip empty values
```html
```
### config="commands"
Type: `property`
The commands, separated with `;`.
The values are kept as strings, because they are compiled as JavaScript.
### element="selector"
Type: `property`
Runs the commands on the elements found by a selector in the whole document.
Example: Update an element elsewhere in the page
```html
```
### child="selector"
Type: `property`
Runs the commands on the elements found by a selector inside the element.
The `value` command needs this attribute or a selector to reach an input.
Example: Fill an input
```html
```
### parent="selector"
Type: `property`
Runs the commands on the closest parent found by a selector.
Example: Change a parent element
```html
```
### plugin="path"
Type: `property`
Creates a plugin on the element itself, and a `?` in the path refers to it.
Example: A binder with its own plugin
```html
```
### .name:expression
Type: `command`
Toggles the CSS class `name` according to the result of the expression.
Example: Toggle classes
```html
```
### text:expression
Type: `command`
Sets the text of the element. HTML is escaped.
A `null`, `undefined`, `false` or empty-string result writes the value of the `empty` command, and `0` is written as `0`. Nothing is written while the element is hidden by `show`, `hide`, `visible` or `invisible`, unless `forcerender` allows it.
Example: Show a text
```html
```
### html:expression
Type: `command`
Sets the HTML content of the element.
It follows the same rules as `text`, without escaping.
Example: Render markup
```html
```
### value selector:expression
Type: `command`
Sets the value of a form control.
Use a selector or the `child` attribute, because the `` element is not a control itself.
Example: Fill an input with a selector
```html
```
### title:expression
Type: `command`
Sets the `title` attribute.
Example: Text and title together
```html
```
### href:expression
Type: `command`
Sets the `href` attribute.
### src:expression
Type: `command`
Sets the `src` attribute.
Example: Set attributes with selectors
```html
```
### attr name [selector]:expression
Type: `command`
Sets the attribute `name`.
Example: Set a custom attribute
```html
```
### show:expression
Type: `command`
Removes the CSS class `hidden` when the result is truthy and adds it otherwise.
Example: Show and hide
```html
Items
Empty
```
### hide:expression
Type: `command`
Adds the CSS class `hidden` when the result is truthy and removes it otherwise.
### visible:expression
Type: `command`
Removes the CSS class `invisible` when the result is truthy and adds it otherwise.
### invisible:expression
Type: `command`
Adds the CSS class `invisible` when the result is truthy and removes it otherwise.
Example: Keep the space of the element
```html
Loaded
```
### forcerender:expression
Type: `command`
Allows `text`, `html` and `template` to render while the element is hidden, when the result is truthy.
Example: Render into a hidden element
```html
```
### template:[{selector}] [selector --> attribute]
Type: `command`
Renders a Tangular template with the value.
The template comes from a `
```
Example: Use an external template and update only changed rows
```html
```
### helpers:path
Type: `command`
Sets the object with the Tangular helpers for the `template` command.
Example: Custom helpers
```html
{{ value | shout }}
```
### format:value
Type: `command`
Formats a `Date` value for the `text`, `html`, `value`, `title`, `href`, `src` and `attr` commands.
Example: Format a date
```html
```
### empty:text
Type: `command`
Sets the text written by `text`, `html`, `value`, `title`, `href` and `src` when the result is `null`, `undefined`, `false` or an empty string.
Without a value, the text in `DEF.empty` is used (`---`).
Example: Show a placeholder
```html
```
### class:name
Type: `command`
Toggles a CSS class on the `` element once, after the commands run for the first time.
Example: Mark the element as rendered
```html
```
### exec:path
Type: `command`
Calls a function with the value, the path and the target element.
A `?` in the value is replaced with the path of the parent plugin. The form `?/method` calls a method of the plugin.
Example: Call a function on each change
```html
```
### refresh:path
Type: `command`
Calls a function with the value, the path and the target element, in the same way as `exec`.
### focus:selector
Type: `command`
Moves the focus to the first visible element found by the selector, 500 milliseconds after the change.
The focus is not moved on mobile devices.
Example: Focus an input
```html
```
### checked:expression
Type: `command`
Sets the `checked` state of the checkboxes and radio buttons inside the target.
Example: Check a checkbox
```html
```
### disabled:expression
Type: `command`
Disables the form controls and the components inside the target when the result is truthy.
Form controls are `input`, `select`, `textarea` and `button`. Components receive the `disabled` config key.
Example: Disable a form
```html
```
### enabled:expression
Type: `command`
Enables the form controls and the components inside the target when the result is truthy, and disables them otherwise.
Example: Enable a button
```html
Save
```
### required:expression
Type: `command`
Sets the `required` config key of the components inside the target.
Example: Require a field
```html
```
### assign:path
Type: `command`
Writes the instance of the binder to a path.
The instance has the method `exec(value, path, [flags])`, which runs the commands with a given value.
Example: Run the commands from code
```html
```
### once
Type: `command`
Runs the commands only one time.
With the `!` prefix in the path, the commands run for the first value that is not empty. Without it, they run with the value that exists when the element is created.
Example: Render the first value
```html
```
### strict
Type: `command`
Ignores changes made in nested paths.
Example: React only to the path itself
```html
```
### track:name[,name]
Type: `command`
Limits changes in nested paths to the listed property names.
A change of the observed path itself, or of a parent path, always runs the commands.
Example: Track one property
```html
```
### changes
Type: `command`
Runs the commands only when the value differs from the previous one.
Example: Ignore identical values
```html
```
### check:path
Type: `command`
Runs the commands only when the function at the path returns a truthy value.
The function receives the value, the path and the `` element.
Example: Filter the values
```html
```
### delay:milliseconds
Type: `command`
Waits for the given time and runs the commands with the last value.
Without a value, the delay is 100 milliseconds.
Example: Group quick changes
```html
```
---
title: ui-component
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/ui-component/
updated: 2026-11-18T13:58:19.462Z
---
# ui-component
> The attributes and the config keys of the ui-component element.
The `` element places an instance of a component declared with `COMPONENT()` in the page. Its attributes are read once, when the element is created. The [Using components](../../guides/using-components/) guide explains how to work with it, and the instance itself is described on the [Component](../component/) page.
## API
### name="component"
Type: `property`
The name of the component declared with `COMPONENT()`. The attribute is required: an element without it is ignored.
When no declaration with this name exists, the library downloads one from the address in the `source` attribute, or from the address in `DEF.fallback`.
A name that starts with `LAZY ` (for example `LAZY dialog`) delays the creation of the instance until the first `SETTER()` call for that component.
Example: Create a component on the first SETTER() call
```html
```
### path="path"
Type: `property`
The path of the value that the component reads and writes.
The value is passed to the `setter` of the component and every change at the path calls it again. A `?` is replaced with the path of the parent plugin. Without this attribute, or with the value `null`, the component has no path. See [Paths](../../guides/paths/).
Example: Bind a component to a path
```html
```
### config="key:value;key:value"
Type: `property`
The configuration of the instance.
Keys and values are separated with `:`, pairs with `;`. Write `\;` and `\:` to use these characters in a value. The values `true` and `false` become booleans and numeric values become numbers. Everything else stays a string.
The keys of the attribute overwrite the default configuration given to `COMPONENT()`.
Example: Read the configuration
```html
```
### default="expression"
Type: `property`
A JavaScript expression that gives the default value of the path.
The expression is evaluated when the component initializes and the value at the path is `null` or `undefined`. The result is written to the path without calling the `setter` a second time. It is evaluated again when a notification with the `@default` flag finds an empty value.
Example: Fill an empty path
```html
```
### source="URL"
Type: `property`
The address of the declaration, used when the component is not declared in the page.
The content at the address is imported once for all elements with the same name, and the waiting instances are created afterwards.
Example: Load the declaration from your own server
```html
```
### plugin="path"
Type: `property`
Creates a plugin on the element itself.
The value has the same form as the `path` attribute of [ui-plugin](../ui-plugin/). The plugin is created first, and a `?` in the path of the component refers to it.
Example: A component with its own plugin
```html
```
### $assign:path
Type: `config`
Writes the component instance to a path.
Example: Keep a reference to the instance
```html
```
### $class:name
Type: `config`
Toggles a CSS class on the element when the component is configured.
Example: Add a class once the component is ready
```html
```
### $id:value
Type: `config`
Sets the `id` of the instance.
The identifier selects the component in `SETTER('#value/method')` and `CONFIG('#value', ...)`.
Example: Call one instance by its identifier
```html
```
### $init:path
Type: `config`
Calls a function when the component is configured.
The function receives the instance. A `?` in the value is replaced with the path of the parent plugin.
Example: Run a function with the instance
```html
```
### $setter:path
Type: `config`
Calls a function after each change of the value.
The function receives `value`, `path` and `flags`, the same arguments as the `setter` delegate.
Example: Observe the value from outside
```html
```
### =key:path
Type: `config`
Keeps the config key `key` equal to the value at a path.
The key is set when the component initializes and on each change at the path. `configure` is called each time.
Example: Drive a config key from the model
```html
```
### =:path
Type: `config`
Applies the object at a path as the configuration.
Each key of the object is set with `reconfigure()` when the component initializes and on each change at the path. The path must contain an object when the component initializes.
Example: Configure a component from an object
```html
```
### type:name
Type: `config`
Converts the value that the component writes with `getter()`.
Supported values are `number`, `currency`, `float`, `boolean`, `bool`, `date` and `datetime`. Any other value leaves the input unchanged.
Example: Store a number
```html
```
### format:value
Type: `config`
The date format used to parse the input when `type` is `date` or `datetime`.
Without this key, the format in `DEF.dateformat` is used.
Example: Parse a custom date format
```html
```
### touched:true
Type: `config`
Marks the component as touched and sets the `ui-touched` class on the element.
### modified:true
Type: `config`
Marks the component as modified and sets the `ui-modified` class on the element.
### invalid:true
Type: `config`
Marks the component as invalid and sets the `ui-invalid` class on the element.
The value is overwritten each time the component validates. When a `validate` delegate returns a string, the key holds that string.
### disabled:true
Type: `config`
Marks the component as disabled and sets the `ui-disabled` class on the element.
Example: State classes
```html
```
### required:true
Type: `config`
Marks the component as required.
The key is set by the `required` command of [ui-bind](../ui-bind/) and is matched by the `@required` flag when components are searched by path. A component reads it in its own code.
---
title: Component
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/component/
updated: 2026-11-18T13:58:19.462Z
---
# Component
> The properties, the methods and the delegates of a component instance.
A component instance is the first argument of the function given to `COMPONENT()`. It is created for each [ui-component](../ui-component/) element. The [Creating components](../../guides/creating-components/) guide shows how the parts work together.
## API
### id
Type: `property`
The identifier of the instance.
Returns: `String` The identifier of the instance.
The value is generated, and the `$id` config key replaces it.
### ID
Type: `property`
The generated identifier of the instance.
Returns: `String` The generated identifier of the instance.
The `$id` config key does not change it.
### name
Type: `property`
The name of the component.
Returns: `String` The name of the component.
### path
Type: `property`
The path of the component, or `null` when the element has none.
Returns: `Path` The path of the component, or `null` when the element has none.
See [Path](../path/).
### config
Type: `property`
The current configuration.
Returns: `Object` The current configuration.
Change it with `reconfigure()`, so that `configure` is called.
### element
Type: `property`
The `` element as a jQuery object.
Returns: `jQuery` The `` element as a jQuery object.
### dom
Type: `property`
The `` element.
Returns: `HTMLElement` The `` element.
### plugin
Type: `property`
The parent plugin, or `null`.
Returns: `Plugin` The parent plugin, or `null`.
See [Plugin](../plugin/).
### scope
Type: `property`
The object that paths are resolved against, which is `window`.
Returns: `Object` The object that paths are resolved against, which is `window`.
### cls
Type: `property`
The CSS class name of the component, for example `ui-grid`.
Returns: `String` The CSS class name of the component, for example `ui-grid`.
The class is not added to the element automatically.
### def
Type: `property`
A function that returns the value of the `default` attribute. It exists only when the attribute is used.
Returns: `Function` A function that returns the value of the `default` attribute. It exists only when the attribute is used.
### ready
Type: `property`
Is `true` once the instance starts to initialize.
Returns: `Boolean` Is `true` once the instance starts to initialize.
### init()
Type: `delegate`
Runs once per declaration, for the first instance of the component.
It runs ahead of `make`. Use it for work shared by all instances.
Example: The order of the delegates
```html
```
### make()
Type: `delegate`
Runs when the instance is created.
Build the content of the element here.
### configure(key, value, init, prev)
Type: `delegate`
Runs for each config key when the configuration changes.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes | | The config key. |
| `value` | `Object` | yes | | The new value. |
| `init` | `Boolean` | yes | | `true` during the initialization. |
| `prev` | `Object` | yes | | The previous value, or `null` during the initialization. |
It runs for all keys when the component initializes.
Example: React to a config key
```html
```
### setter(value, path, flags)
Type: `delegate`
Receives each change of the value at the path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes | | The current value. |
| `path` | `String` | yes | | The path that changed. |
| `flags` | `Object` | yes | | The flags of the change, for example `{ init: 1 }`. |
The default implementation writes the value to the first `input`, `textarea` or `select` inside the element. A checkbox is checked when the value, as text, is `true`, `1`, `on`, `yes` or `ok`. Assign your own function to render the value.
Example: Render the value
```html
```
### setter2(value, path, flags)
Type: `delegate`
Receives each change of the value, including the changes written with `rewrite()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes | | The current value. |
| `path` | `String` | yes | | The path that changed. |
| `flags` | `Object` | yes | | The flags of the change. |
Example: See the values that skip the setter
```html
```
### getter(value, [realtime])
Type: `delegate`
Processes a value entered by the user and writes it to the path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes | | The entered value. |
| `realtime` | `Boolean` | no | `false` | Writes the value without calling the `setter`. |
The value goes through the function set with `parser()` and is converted according to the `type` config key. With `realtime`, the value is written without calling the `setter`.
Example: Write a value from code
```js
com.getter('5');
console.log(common.value);
// logs: 5
```
### validate(value)
Type: `delegate`
Decides whether the value is valid.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes | | The value to check. |
Returns: `Boolean` The result of the validation. A string is also accepted.
Return `true` or an empty string for a valid value. A returned string is stored in `config.invalid` as the message, and any other result sets `config.invalid` to `true`. The method runs after each change of the value.
Example: Require a value
```html
```
### state()
Type: `delegate`
Runs when the state of the component changes.
Read the state from `config.touched`, `config.modified`, `config.invalid` and `config.disabled`.
Example: Follow the state
```html
```
### state2(component)
Type: `delegate`
Runs when another component with the same path reports its state.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `component` | `Component` | yes | | The component that reports the state. |
The report is made with `validate2()` or with the `notify` flag of `bind()`.
Example: Listen to a sibling
```html
```
### done()
Type: `delegate`
Runs at the end of the initialization, when the value is set.
### destroy()
Type: `delegate`
Runs when the instance is removed.
It is called by `remove()`, and by the regular cleanup for elements that left the page. Release timers and global handlers here.
Example: Clean up
```html
```
### get()
Type: `method`
Reads the value at the path of the component.
Returns: `Object` The value, or `null` without a path.
Example: Read the value
```js
SET('common.value', 1);
console.log(com.get());
// logs: 1
```
### set(value, [flags])
Type: `method`
Writes a value to the path and notifies everything bound to it.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes | | The value to write. |
| `flags` | `String` | no | | Flags such as `@touched @modified`. |
Example: Write the value
```js
com.set(5, '@touched');
console.log(common.value);
// logs: 5
```
### rewrite(value, [flags])
Type: `method`
Writes a value to the path without calling the `setter` of this instance.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes | | The value to write. |
| `flags` | `String` | no | | Flags such as `@touched @modified`. |
Other components and watchers are notified.
Example: Write without rendering
```js
com.rewrite(7);
console.log(com.get());
// logs: 7
```
### modify(value, [flags])
Type: `method`
Writes a value and marks the component as touched and modified.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes | | The value to write. |
| `flags` | `String` | no | | Flags such as `@touched @modified`. |
Example: Write a value entered by the user
```js
com.modify('x');
console.log(com.element.attr('class'));
// logs: ui-touched ui-modified
```
### push(value)
Type: `method`
Adds a value to the array at the path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes | | The value to write. |
An empty path is initialized with a new array and a single value is wrapped in an array.
Example: Add an item
```js
com.push('a');
com.push('b');
console.log(common.value.join());
// logs: a,b
```
### upd([flags])
Type: `method`
Notifies everything bound to the path, without changing the value.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `flags` | `String` | no | | Flags such as `@touched @modified`. |
The method is also available as `update()`.
Example: Announce a change made directly
```js
common.value = 5;
com.upd();
console.log(com.get());
// logs: 5
```
### refresh()
Type: `method`
Calls the `setter` with the current value.
Example: Render again
```html
```
### setPath(path)
Type: `method`
Changes the path of the component.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The new path. |
A `?` is replaced with the path of the parent plugin. The `setter` is not called until the next change, so call `refresh()` to render the new value.
Example: Point the component to another value
```js
com.setPath('common.other');
console.log(com.path.toString());
// logs: common.other
```
### makepath(path)
Type: `method`
Replaces the `?` in a path with the path of the parent plugin.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path. |
Returns: `String` The resulting path.
Example: Resolve a relative path
```html
```
### bind(flags, [value])
Type: `method`
Changes the state of the component and optionally writes a value without calling the `setter`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `flags` | `String` | yes | | The flags. |
| `value` | `Object` | no | | The value to write. |
The flags are separated with a space, a comma or `|`, with or without `@`:
| Flag | Effect |
| --- | --- |
| `touched`, `touch` | Marks the component as touched. |
| `modified`, `changed`, `modify`, `change` | Marks the component as modified. |
| `reset` | Clears the touched and modified state. |
| `validate` | Runs the validation. |
| `notify` | Calls `state2` of the other components with the same path. |
| `setter` | Calls the `setter`. |
Example: Mark a value as entered by the user
```js
com.bind('@touched @modified', 'x');
console.log(com.get(), com.element.attr('class'));
// logs: x ui-touched ui-modified
```
### touch()
Type: `method`
Marks the component as touched and runs the validation.
Example: Mark as touched
```js
com.touch();
console.log(com.config.touched);
// logs: 1
```
### change()
Type: `method`
Marks the component as touched and modified and runs the validation.
Example: Mark as changed
```js
com.change();
console.log(com.element.attr('class'));
// logs: ui-touched ui-modified
```
### reset([noemit])
Type: `method`
Clears the touched and modified state.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `noemit` | `Boolean` | no | `false` | Skips the validation. |
The validation runs unless `noemit` is `true`.
Example: Clear the state
```js
com.change();
com.reset();
console.log(com.config.touched, com.config.modified);
// logs: 0 0
```
### isInvalid()
Type: `method`
Tells whether the component is touched and invalid.
Returns: `Boolean` A truthy value when the component is touched and invalid.
Example: Show an error only after the user was here
```html
```
### validate2([value])
Type: `method`
Runs the validation and calls `state2` of the other components with the same path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | no | | The value to validate. The default is the current value. |
### reconfigure(value)
Type: `method`
Changes the configuration and calls `configure` for each key.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes | | The keys to change. |
The value is an object or a string in the form `key:value;key:value`. It accepts the special keys of the [ui-component](../ui-component/) element, such as `$class` and `=key`.
Example: Change the configuration
```js
com.reconfigure('title:Orders;limit:5');
console.log(com.config.title, com.config.limit);
// logs: Orders 5
```
### watchconfig(key, path)
Type: `method`
Keeps a config key equal to the value at a path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String` | yes | | The config key, or `null`. |
| `path` | `String` | yes | | The path to observe. |
With `null` as the key, the object at the path is applied as the configuration.
Example: Follow a value
```js
com.watchconfig('limit', 'common.limit');
SET('common.limit', 10);
console.log(com.config.limit);
// logs: 10
```
### formatter(fn)
Type: `method`
Sets a function that converts the value for display, or converts a value with it.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes | | A function `(path, value, type, format)` that returns the value to display, or the value to convert. |
Returns: `Object` The converted value, when a value is given.
With a function as the argument, the default `setter` uses it from then on. With any other value, the method returns the converted value.
Example: Format a price
```html
```
### parser(fn)
Type: `method`
Sets a function that converts the entered value for the model, or converts a value with it.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes | | A function `(path, value, type, format)` that returns the value to store, or the value to convert. |
Returns: `Object` The converted value, when a value is given.
With a function as the argument, `getter()` uses it from then on. With any other value, the method returns the converted value.
Example: Parse a price
```html
```
### autobind20([delay], [realtimebinding])
Type: `method`
Connects the `input`, `select` and `textarea` inside the element with the path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `delay` | `Number` | no | `200` | The delay in milliseconds. |
| `realtimebinding` | `Boolean` | no | `false` | Calls the `setter` also while the user types. |
The value is written after the delay, and the touched and modified states are updated from the user events.
Example: Bind an input
```html
```
### autofill([enabled])
Type: `method`
Writes the values that the browser fills in on its own to the model.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `enabled` | `Boolean` | no | `true` | `false` turns the feature off. |
A browser can fill a form with saved data, such as a name or an address, without any input event. One second after the library starts, it reads the first `input`, `textarea` or `select` of each component that calls this method, and a value found there is written to the path with the flags `@change` and `@init`. The parser of the component converts the value first.
It works with the default `setter`. Components with a `default` attribute, `select` elements and range inputs are skipped. `autofill(false)` turns it off.
Example: Keep a value filled in by the browser
```html
```
### readonly()
Type: `method`
Turns the component into a display without `getter`, `setter` and validation.
### blind()
Type: `method`
Excludes the component from notifications and from searches by path.
### singleton()
Type: `method`
Allows only one instance of the component.
Other `` elements with the same name are removed.
Example: Keep one instance
```html
```
### watch(path, callback, [autoinit])
Type: `method`
Calls a function on each change at a path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path to observe. |
| `callback` | `Function` | yes | | A function `(value, flags, path)`. |
| `autoinit` | `Boolean` | no | `false` | Calls the function right away with the current value. |
Join several paths with `+`. With a function as the first argument, the path of the component is observed. A `?` is replaced with the path of the parent plugin.
Example: Observe another path
```js
com.watch('common.user', (value, flags, path) => console.log(value, path));
SET('common.user', 'Anna');
// logs: Anna common.user
```
### unwatch(path, [callback])
Type: `method`
Removes watchers registered with `watch()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The observed path. |
| `callback` | `Function` | no | | The watcher to remove. |
Without `callback`, all the watchers of the path registered by this component are removed. With a function as the only argument, the watcher of the component path is removed. Join several paths with `+`. A `?` is replaced with the path of the parent plugin.
Example: Stop observing a path
```js
var log = value => console.log('changed', value);
com.watch('common.count', log);
SET('common.count', 1);
com.unwatch('common.count', log);
SET('common.count', 2);
// logs: changed 1
```
### datasource(path, callback, [init])
Type: `method`
Observes a path with data for the component.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path to observe. |
| `callback` | `Function` | yes | | A function `(value, flags, path)`. |
| `init` | `Boolean` | no | `true` | Set `false` to skip the first call. |
Returns: `Component` The instance.
The function is called with the current value when the component initializes, unless `init` is `false`, and on each change. A new call replaces the data source registered before, and `datasource(null)` removes it.
Example: Render items from a path
```html
```
### on(name, callback)
Type: `method`
Registers a handler of a global event.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The event name. |
| `callback` | `Function` | yes | | The handler. |
Join several event names with `+`. See [Events](../events/).
Example: Handle an event
```js
var handler = value => console.log(value);
com.on('refresh', handler);
EMIT('refresh', 1);
com.off('refresh', handler);
EMIT('refresh', 2);
// logs: 1
```
### off(name, [callback])
Type: `method`
Removes a handler of a global event.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The event name. |
| `callback` | `Function` | no | | The handler to remove. |
Without a callback, all handlers of the event registered on this instance are removed.
### emit(name, [a], [b], [c], [d])
Type: `method`
Emits a global event.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The event name. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
Example: Emit an event
```js
ON('saved', value => console.log(value));
com.emit('saved', 'ok');
// logs: ok
```
### command(name, callback)
Type: `method`
Registers a command of this instance.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The command name. |
| `callback` | `Function` | yes | | The handler. |
Example: Register and run a command
```js
com.command('clear', value => console.log('clear', value));
com.CMD('clear', 1);
// logs: clear 1
```
### CMD(name, [a], [b], [c], [d], [e])
Type: `method`
Runs a command registered on this instance with `command()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The command name. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
| `e` | `Object` | no | | The fifth argument. |
### GET(path)
Type: `method`
Reads a value from a path. A `?` is replaced with the path of the parent plugin.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path. |
Returns: `Object` The value.
Example: Work with the model of the plugin
```html
```
### SET(path, value)
Type: `method`
Writes a value to a path and notifies everything bound to it. A `?` is replaced with the path of the parent plugin.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path. |
| `value` | `Object` | yes | | The value to write. |
### EXEC(name, [a], [b], [c], [d])
Type: `method`
Calls a function or a plugin method.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | For example `FUNC.save`, `?/save` or `@save`. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
A `?` is replaced with the path of the parent plugin. A name that starts with `@` calls a method of the closest parent component.
Example: Call a method of the parent component
```html
```
### SEEX(name, [a], [b], [c], [d])
Type: `method`
Calls a plugin method or a global function, or writes the first argument to the path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The method, the function or the path. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
The form `plugin/method` calls a method of the plugin and a name of a global function calls that function. Any other name is a path that receives `a`.
Example: Write to a path
```js
com.SEEX('common.status', 'done');
console.log(common.status);
// logs: done
```
### SETTER(name, [a], [b], [c], [d])
Type: `method`
Calls a method of components in the whole page, in the form `component/method`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The target, for example `grid/refresh`. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
Example: Call a method of another component
```html
```
### find(selector)
Type: `method`
Finds elements inside the component.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `selector` | `String` | yes | | A selector, or an object with selectors. |
Returns: `jQuery` The found elements, or an object of them.
With an object, the method searches for each selector and returns an object with the same keys.
Example: Find elements
```html
```
### closest(selector)
Type: `method`
Finds the closest parent that matches a selector.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `selector` | `String` | yes | | A jQuery selector. |
Returns: `jQuery` The found element.
Example: Find a parent
```js
console.log(com.closest('body')[0].tagName);
// logs: BODY
```
### parent([selector])
Type: `method`
Finds a parent element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `selector` | `String` | no | | The selector. |
Returns: `jQuery` The found element.
Without an argument, the method returns the direct parent. These values are also supported:
| Selector | Result |
| --- | --- |
| `auto` | The closest parent with a height set in its style, or `window` |
| `window` | The `window` object as jQuery |
| `document` | The `document` as jQuery |
| `parent` followed by a number | The parent that many levels above the direct parent |
| anything else | The closest parent that matches the selector |
Example: Read the direct parent
```js
console.log(com.parent()[0].tagName);
// logs: BODY
```
### html([value])
Type: `method`
Reads or replaces the HTML of the element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | no | | The new content. |
Returns: `jQuery` The element, or the current HTML without an argument.
An array is joined into one string.
Example: Set the content
```js
com.html(['', 'Hello', ' ']);
console.log(com.html());
// logs: Hello
```
### text([value])
Type: `method`
Reads or replaces the text of the element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | no | | The new text. |
Returns: `jQuery` The element, or the current text without an argument.
An array is joined into one string.
Example: Set the text
```js
com.text('Hello');
console.log(com.text());
// logs: Hello
```
### append(value)
Type: `method`
Adds HTML to the end of the element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes | | The content. |
Returns: `jQuery` The element.
An array is joined into one string.
Example: Add content
```js
com.append(' ');
com.append(['', ' ']);
console.log(com.html());
// logs:
```
### empty()
Type: `method`
Removes the content of the element.
Returns: `Component` The instance.
### attr(name, [value])
Type: `method`
Reads or sets an attribute of the element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The attribute. |
| `value` | `String` | no | | The new value. |
Returns: `Object` The value when reading, the instance when setting.
Example: Attributes
```js
com.attr('title', 'Hello');
com.attrd('id', 5);
console.log(com.attr('title'), com.attrd('id'));
// logs: Hello 5
```
### attrd(name, [value])
Type: `method`
Reads or sets a `data-` attribute of the element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name without the `data-` prefix. |
| `value` | `String` | no | | The new value. |
Returns: `String` The value when reading.
### css(name, [value])
Type: `method`
Reads or sets a CSS property of the element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The property. |
| `value` | `String` | no | | The new value. |
Returns: `Object` The value when reading, the instance when setting.
Example: Change a style
```js
com.css('color', 'red');
console.log(com.css('color'));
// logs: rgb(255, 0, 0)
```
### aclass(name, [timeout])
Type: `method`
Adds a CSS class to the element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The class. |
| `timeout` | `Number` | no | | A delay in milliseconds. |
Returns: `Component` The instance.
Example: Work with classes
```js
com.aclass('a b');
com.rclass('a');
com.tclass('c');
console.log(com.element.attr('class'), com.hclass('c'));
// logs: b c true
```
### rclass([name], [timeout])
Type: `method`
Removes a CSS class from the element, or all classes without an argument.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no | | The class. |
| `timeout` | `Number` | no | | A delay in milliseconds. |
Returns: `Component` The instance.
### rclass2(search)
Type: `method`
Removes all CSS classes that contain a text.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `search` | `String` | yes | | The text to search for. |
Returns: `Component` The instance.
Example: Remove a group of classes
```js
com.aclass('size-1 size-2 box');
com.rclass2('size-');
console.log(com.element.attr('class'));
// logs: box
```
### tclass(name, [enable])
Type: `method`
Toggles a CSS class on the element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The class. |
| `enable` | `Boolean` | no | | Forces the state of the class. |
Returns: `Component` The instance.
### hclass(name)
Type: `method`
Tells whether the element has a CSS class.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The class. |
Returns: `Boolean` `true` when the class is present.
### width()
Type: `method`
Returns the width of the element in pixels.
Returns: `Number` The width.
### height()
Type: `method`
Returns the height of the element in pixels.
Returns: `Number` The height.
### event(name, [selector], callback)
Type: `method`
Registers a DOM event handler on the element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The DOM event. |
| `selector` | `String` | no | | Limits the event to matching children. |
| `callback` | `Function` | yes | | The handler. |
Returns: `Component` The instance.
The arguments are passed to the jQuery `.on()` method.
Example: Handle a click
```html
Save
```
### autofocus([selector])
Type: `method`
Moves the focus to the first visible control inside the element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `selector` | `String` | no | | The elements to focus. |
Returns: `Component` The instance.
The default selector is `input,select,textarea`. When no control can take the focus yet, the method tries again every 200 milliseconds, 15 times at most. The focus is not moved on mobile devices.
Example: Focus the first input
```html
```
### import(url, [callback], [prepare])
Type: `method`
Downloads content and appends it to the element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes | | The address. |
| `callback` | `Function` | no | | Runs when the content is in the page. |
| `prepare` | `Function` | no | | A function `(html)` that returns the content to insert. |
See `IMPORT()` in [Importing content](../../guides/importing/).
Example: Import a part
```js
com.import('/parts/help.html', () => console.log(com.html()), html => html + ' ');
// logs: Help
```
### replace(target, [remove])
Type: `method`
Moves the component to another element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `target` | `Element` | yes | | The new element, as a selector, a DOM element or jQuery. |
| `remove` | `Boolean` | no | `false` | Removes the original element. |
Returns: `Component` The instance.
With `remove`, the original element is removed from the page.
Example: Move the component
```js
com.replace('#box', true);
console.log(com.dom.id, $('ui-component').length);
// logs: box 0
```
### remove()
Type: `method`
Calls `destroy` and removes the component and its element.
### icon(value)
Type: `method`
Adds the icon prefix in `DEF.iconprefix` to an icon name.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes | | The icon name. |
Returns: `String` The CSS classes of the icon.
A value with a space already contains its prefix and stays unchanged.
Example: Build icon classes
```js
console.log(com.icon('home'));
// logs: ti ti-home
console.log(com.icon('fa fa-home'));
// logs: fa fa-home
```
### caniuse(name)
Type: `method`
Finds the first declared component in a list of names separated with a comma or `|`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The names. |
Returns: `String` The found name, or `false`.
Example: Choose an available component
```js
console.log(com.caniuse('missing,demo'));
// logs: demo
console.log(com.caniuse('missing|demo'));
// logs: demo
console.log(com.caniuse('missing'));
// logs: false
```
### parseSource(value)
Type: `method`
Parses a list in the form `id|name|icon,id|name|icon`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes | | The list. |
Returns: `Array` Objects with `id`, `name` and `icon`.
The method is also available as `parsesource()`. When the `type` config key is `number`, the identifiers are converted to numbers.
Example: Parse a list
```js
var items = com.parseSource('1|One,2|Two|home');
console.log(JSON.stringify(items[1]));
// logs: {"id":"2","name":"Two","icon":"home"}
```
---
title: ui-plugin
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/ui-plugin/
updated: 2026-11-18T13:58:19.462Z
---
# ui-plugin
> The attributes and the config keys of the ui-plugin element.
The `` element creates an instance of a plugin declared with `PLUGIN()` and gives the elements inside it a common path. The [Plugins](../../guides/plugins/) guide explains how to work with it, and the instance is described on the [Plugin](../plugin/) page.
## API
### path="path"
Type: `property`
The path of the plugin model, and the name of the declaration to use.
The attribute accepts these forms:
| Value | Model path | Declaration |
| --- | --- | --- |
| `orders` | `orders` | `orders` |
| `target name` | `target` | `name` |
| `? name` | a generated path under `jComponent.data.` | `name` |
| `*` | `common` | `PLUGIN('*', ...)` |
| no attribute | the name of the next declaration waiting for an element | that declaration |
When no declaration exists for the path, the element still works as a plugin without its own code.
Example: One declaration, two models
```html
```
Example: A generated model path
```html
```
### config="key:value;key:value"
Type: `property`
The configuration of the plugin instance.
The format is the same as in [ui-component](../ui-component/). Besides the keys below, the plugin reads any key of its own from `exports.config`.
Example: Read the configuration
```html
```
### init:path
Type: `config`
Calls a function when the plugin is created, just ahead of `make`.
The function receives the jQuery element of the plugin. A `?` in the value is replaced with the path of the plugin, so `?/ready` calls the `ready` method of the same plugin.
Example: Call a method of the plugin
```html
```
### class:name
Type: `config`
Toggles a CSS class on the element 500 milliseconds after the plugin is created.
Example: Reveal the plugin
```html
```
### aclass:true
Type: `config`
Adds the value of the `path` attribute to the element as a CSS class.
Example: Style the plugin by its name
```html
```
---
title: Plugin
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/plugin/
updated: 2026-11-18T13:58:19.462Z
---
# Plugin
> The properties, the methods and the delegates of a plugin instance.
A plugin instance is the first argument of the function given to `PLUGIN()`, usually named `exports`. It is created for each [ui-plugin](../ui-plugin/) element. The methods work with paths relative to the plugin, as explained in the [Plugins](../../guides/plugins/) guide. The examples below use a plugin with the path `orders`.
## API
### name
Type: `property`
The path of the plugin.
Returns: `String` The path of the plugin.
### path
Type: `property`
The path of the plugin model.
Returns: `Path` The path of the plugin model.
See [Path](../path/).
### config
Type: `property`
The configuration of the plugin.
Returns: `Object` The configuration of the plugin.
### element
Type: `property`
The element of the plugin as a jQuery object.
Returns: `jQuery` The element of the plugin as a jQuery object.
### dom
Type: `property`
The element of the plugin.
Returns: `HTMLElement` The element of the plugin.
### scope
Type: `property`
The object that paths are resolved against, which is `window`.
Returns: `Object` The object that paths are resolved against, which is `window`.
### cls
Type: `property`
The value of the `path` attribute of the element.
Returns: `String` The value of the `path` attribute of the element.
### ready
Type: `property`
Is `true` when the plugin is initialized.
Returns: `Boolean` Is `true` when the plugin is initialized.
### plugin
Type: `property`
The parent plugin of a plugin nested with a `?` in its path, otherwise `null`.
Returns: `Plugin` The parent plugin of a plugin nested with a `?` in its path, otherwise `null`.
### parent
Type: `property`
The same value as the `plugin` property.
Returns: `Plugin` The same value as the `plugin` property.
Example: A nested plugin
```html
```
### caller
Type: `property`
The plugin that called a method of this plugin through `EXEC()`.
Returns: `Plugin` The plugin that called a method of this plugin through `EXEC()`.
See `talker()`.
### model
Type: `property`
Reads or replaces the model of the plugin.
Returns: `Object` Reads or replaces the model of the plugin.
Assigning a value does not notify anything bound to the path. Use `set()` or `upd()` for that.
Example: Read the model
```js
plugin.set('count', 2);
console.log(JSON.stringify(plugin.model));
// logs: {"count":2}
plugin.model = { count: 3 };
console.log(orders.count);
// logs: 3
```
### modified
Type: `property`
Returns the model and clears the state of its components.
Returns: `Object` The model of the plugin.
Reading the property returns the whole model, like `get()`, and clears the touched and modified state of the components in the plugin, like the flag `@reset`. Read it after saving a form.
Example: Save a form
```html
```
### data
Type: `property`
The same value as the `model` property.
Returns: `Object` The same value as the `model` property.
### form
Type: `property`
Returns the model and clears the touched and modified state of the components in the path of the plugin.
Returns: `Object` Returns the model and clears the touched and modified state of the components in the path of the plugin.
Example: Read a form and reset its state
```html
```
### make()
Type: `delegate`
Runs when the plugin is created.
Example: Initialize the plugin
```html
```
### destroy()
Type: `delegate`
Runs when the plugin is removed.
The regular cleanup removes the plugins whose element left the page.
Example: Release resources
```html
```
### get([path])
Type: `method`
Reads a value from the model.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | no | | A path relative to the plugin. |
Returns: `Object` The value.
Without a path, the method returns the whole model. A path with the `@reset` flag also clears the state of the components in the path.
Example: Read a value
```js
plugin.set('user.name', 'Anna');
console.log(plugin.get('user.name'));
// logs: Anna
```
### set([path], value)
Type: `method`
Writes a value to the model and notifies everything bound to the path.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | A path relative to the plugin. |
| `value` | `Object` | yes | | The value to write. |
With an object as the only argument, the method replaces the whole model.
Example: Write a value
```js
plugin.set('status', 'open');
console.log(orders.status);
// logs: open
```
Example: Replace the model
```js
plugin.set({ status: 'new', items: [] });
console.log(JSON.stringify(orders));
// logs: {"status":"new","items":[]}
```
### push(path, value)
Type: `method`
Adds a value to an array in the model.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | A path relative to the plugin. |
| `value` | `Object` | yes | | The value to write. |
Each item of an array value is added separately.
Example: Add items
```js
plugin.push('items', 1);
plugin.push('items', [2, 3]);
console.log(orders.items.join());
// logs: 1,2,3
```
### inc(path, [value])
Type: `method`
Increases a number in the model.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | A path relative to the plugin. |
| `value` | `Number` | no | `1` | The increment. |
Example: Count
```js
plugin.inc('count');
plugin.inc('count', 4);
console.log(orders.count);
// logs: 5
```
### toggle(path)
Type: `method`
Negates a value in the model.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | A path relative to the plugin. |
Example: Switch a value
```js
plugin.toggle('open');
console.log(orders.open);
// logs: true
```
### nul(path)
Type: `method`
Writes `null` to the model.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | A path relative to the plugin. |
Example: Clear a value
```js
plugin.set('user', 'Anna');
plugin.nul('user');
console.log(orders.user);
// logs: null
```
### upd(path)
Type: `method`
Notifies everything bound to a path, without changing the value.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | A path relative to the plugin. |
The method is also available as `update()`.
Example: Announce a direct change
```js
plugin.watch('count', value => console.log(value));
orders.count = 5;
plugin.upd('count');
// logs: 5
```
### watch(path, callback, [autoinit])
Type: `method`
Calls a function on each change at a path of the model.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | A path relative to the plugin. |
| `callback` | `Function` | yes | | A function `(value, flags, path)`. |
| `autoinit` | `Boolean` | no | `false` | Calls the function right away with the current value. |
With a function as the first argument, the whole model is observed. Join several paths with `+`.
Example: Observe a value
```js
plugin.watch('status', (value, flags, path) => console.log(value, path));
plugin.set('status', 'open');
// logs: open orders.status
```
### unwatch(path, [callback])
Type: `method`
Removes watchers registered with `watch()`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | A path relative to the plugin. |
| `callback` | `Function` | no | | The watcher to remove. |
Without `callback`, all the watchers of the path are removed. With a function as the only argument, the watcher of the whole model is removed. Join several paths with `+`.
Example: Stop observing a value
```js
var log = value => console.log('status', value);
plugin.watch('status', log);
plugin.set('status', 'open');
plugin.unwatch('status', log);
plugin.set('status', 'closed');
// logs: status open
```
### makepath(path)
Type: `method`
Replaces the `?` in a path with the path of the plugin.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | The path. |
Returns: `String` The resulting path.
Example: Build a path
```js
console.log(plugin.makepath('?.items'));
// logs: orders.items
```
### cachepath(path, expire, [def])
Type: `method`
Keeps a value of the model in the cache between visits.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes | | A path relative to the plugin. |
| `expire` | `String` | yes | | The lifetime of the saved value, for example `1 day`. |
| `def` | `Object|Function` | no | | The value used when nothing is saved. |
The same as the global [CACHEPATH()](../globals/), with a path relative to the plugin.
Example: Remember a filter
```js
plugin.cachepath('filter', '1 day', 'all');
console.log(orders.filter);
// logs: all
```
### format(value)
Type: `method`
Inserts the path of the plugin into a text.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `String` | yes | | The text. |
Returns: `String` The resulting text.
The text `{0}` is replaced with the path. Without `{0}`, the path is added to the end of the text.
Example: Insert the path
```js
console.log(plugin.format('{0}.items'));
// logs: orders.items
```
### exec(name, [a], [b], [c], [d], [e])
Type: `method`
Calls a method of this plugin.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The method name. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
| `e` | `Object` | no | | The fifth argument. |
The name can carry flags. The method runs without `this`, so refer to the plugin with `exports`.
Example: Call a method
```js
plugin.exec('save', 1);
// logs: save 1
```
### cmd(name, [a], [b], [c], [d])
Type: `method`
Runs a command on the components inside the plugin element.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The command, optionally followed by flags. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
Components register commands with [command()](../component/). `CMD()` is the same method. To reach the components of the whole page, use the global [CMD()](../globals/).
Example: Clear the lists of a plugin
```html
```
### setter(name, [a], [b], [c], [d])
Type: `method`
Calls a method of the components inside the plugin, in the form `component/method`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The target, for example `grid/refresh`. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
The method is also available as `SETTER()`.
Example: Call components inside the plugin
```html
```
### alias(name)
Type: `method`
Registers the plugin under another name in `PLUGINS`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The other name. |
Example: Use a short name
```js
plugin.alias('o');
console.log(PLUGINS.o === plugin);
// logs: true
```
### talker()
Type: `method`
Marks this plugin as the caller of the next `EXEC()` call.
The called plugin finds it in its `caller` property.
Example: Find out who called
```html
```
### on(name, callback)
Type: `method`
Registers a handler of a global event.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The event name. |
| `callback` | `Function` | yes | | The handler. |
Join several event names with `+`. See [Events](../events/).
Example: Handle an event
```js
var handler = value => console.log(value);
plugin.on('saved', handler);
plugin.emit('saved', 1);
plugin.off('saved', handler);
plugin.emit('saved', 2);
// logs: 1
```
### off(name, [callback])
Type: `method`
Removes a handler of a global event.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The event name. |
| `callback` | `Function` | no | | The handler to remove. |
Without a callback, all handlers of the event registered on this plugin are removed.
### emit(name, [a], [b], [c], [d])
Type: `method`
Emits a global event.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The event name. |
| `a` | `Object` | no | | The first argument. |
| `b` | `Object` | no | | The second argument. |
| `c` | `Object` | no | | The third argument. |
| `d` | `Object` | no | | The fourth argument. |
### ajax(url, [data], [callback])
Type: `method`
Sends a request.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes | | The method and the address. |
| `data` | `Object` | no | | The data to send. |
| `callback` | `Function` | no | | A function `(response)`, or a path. |
The address has the form `METHOD /url`. A string as the callback is a path relative to the plugin that receives the response.
Example: Store the response in the model
```js
plugin.ajax('GET /api/orders/', 'items');
console.log(orders.items.length);
// logs: 2
```
### tapi(name, [data], [callback])
Type: `method`
Calls an operation of the API at the address in `DEF.api`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the operation. |
| `data` | `Object` | no | | The data to send. |
| `callback` | `Function` | no | | A function `(response)`, or a path. |
A string as the callback is a path relative to the plugin that receives the response.
Example: Call an API operation
```js
DEF.api = '/api/';
plugin.tapi('orders_list', 'items');
// sends: POST /api/ {"schema":"orders_list"}
```
### pipe(name, [data], [callback])
Type: `method`
Calls an operation of the API at the address in `DEF.pipe`.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the operation. |
| `data` | `Object` | no | | The data to send. |
| `callback` | `Function` | no | | A function `(response)`, or a path. |
It works in the same way as `tapi()`.
Example: Call a pipe operation
```js
DEF.pipe = '/pipe/';
plugin.pipe('orders_save', { id: 1 }, response => console.log(response.ok));
// logs: true
```
---
title: ui-import
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/ui-import/
updated: 2026-11-18T13:58:19.462Z
---
# ui-import
> The attributes and the config keys of the ui-import element.
The `` element downloads content from your server and inserts it into the page. It uses `IMPORT()`, described in the [Importing content](../../guides/importing/) guide together with the flags that the address accepts.
## API
### path="URL"
Type: `property`
The address of the content.
The address can carry the flags of `IMPORT()`, for example `/parts/menu.html @prepend`. The content is appended to the element unless `target` says otherwise.
Example: Import a part of the page
```html
```
### config="key:value;key:value"
Type: `property`
The options of the import.
The format is the same as in [ui-component](../ui-component/).
### plugin="path"
Type: `property`
Creates a plugin on the element itself.
The plugin is created ahead of the download, so the imported content can use its path.
Example: Import into a new plugin
```html
```
### url:address
Type: `config`
The address of the content, used when the `path` attribute is empty.
Example: Set the address in the configuration
```html
```
### target:selector
Type: `config`
Inserts the content into another element.
Example: Choose where the content goes
```html
```
### path:value
Type: `config`
Replaces the keywords `~PATH~` and `CLASS` in the imported content.
The value is also added to `` elements without a `path` attribute, and given as the name to a `PLUGIN(function(...` declaration without a name.
Example: Reuse one part with different paths
```html
```
### id:value
Type: `config`
Replaces the keyword `~ID~` in the imported content.
### init:path
Type: `config`
Calls a function when the content is in the page.
A value that starts with `?` refers to the closest plugin of the target element.
Example: Run code after the import
```html
```
### class:name
Type: `config`
Toggles a CSS class on the target element when the content is in the page.
Example: Mark the element as loaded
```html
```
---
title: Tangular helpers
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/tangular-helpers/
updated: 2026-11-18T13:58:19.462Z
---
# Tangular helpers
> The helpers available in every Tangular template for encoding, formatting and reading code lists.
A helper follows the value in a template, as in `{{ price | format(2) }}`, and helpers can be chained. A value with no helper is encoded with `encode`. To write templates and register custom helpers, see [Templates with Tangular](../../guides/tangular/).
## API
### {{ id | cl(name, [key]) }}
Type: `method`
Writes a field of an item in a code list.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The code list name. |
| `key` | `String` | no | `name` | The field to write. |
Returns: `String` The value of the field.
The code list is the array in `DEF.cl[name]`, and the item is found by its `id`. When nothing is found, the helper writes `DEF.empty`, or an empty string when `key` is set.
Example: Reading a code list
```js
DEF.cl.colors = [{ id: 2, name: 'Red', code: 'R' }];
console.log(Tangular.render("{{ id | cl('colors') }}", { id: 2 })); // Red
console.log(Tangular.render("{{ id | cl('colors', 'code') }}", { id: 2 })); // R
console.log(Tangular.render("{{ id | cl('colors') }}", { id: 9 })); // ---
```
### {{ id | clcolor(name, [key]) }}
Type: `method`
Writes an item of a code list as a colored label.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The code list name. |
| `key` | `String` | no | `name` | The field to write. |
Returns: `String` The HTML of the label.
The helper writes a `` with the item color as its background, the item icon and the field. It writes an empty string when the item is not found. The output is not encoded.
Example: A colored label
```js
DEF.cl.colors = [{ id: 2, name: 'Red', icon: 'ti ti-circle', color: '#f00' }];
console.log(Tangular.render("{{ id | clcolor('colors') }}", { id: 2 })); // Red
```
### {{ id | clicon(name, [key]) }}
Type: `method`
Writes an item of a code list with its icon.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The code list name. |
| `key` | `String` | no | `name` | The field to write. |
Returns: `String` The HTML of the item.
The icon takes the item color. An item without an icon writes only the field, and an item that is not found writes an empty string. The output is not encoded.
Example: An item with an icon
```js
DEF.cl.colors = [{ id: 1, name: 'Plain' }, { id: 2, name: 'Red', icon: 'ti ti-circle', color: '#f00' }];
console.log(Tangular.render("{{ id | clicon('colors') }}", { id: 2 })); // Red
console.log(Tangular.render("{{ id | clicon('colors') }}", { id: 1 })); // Plain
```
### {{ value | currency([name]) }}
Type: `method`
Formats a number or a numeric string with a registered currency.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no | `DEF.currency` | The currency name. |
Returns: `String` The formatted price.
The helper uses [currency()](../number/). A value of another type writes an empty string.
Example: Prices
```js
DEF.currencies.eur = value => value.format(2) + ' EUR';
console.log(Tangular.render("{{ price | currency('eur') }}", { price: 5 })); // 5.00 EUR
console.log(Tangular.render("{{ price | currency('eur') }}", { price: '7.5' })); // 7.50 EUR
```
### {{ value | def([text], [raw]) }}
Type: `method`
An alias of the `empty` helper.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `text` | `String` | no | `DEF.empty` | The text for an empty value. |
| `raw` | `Boolean` | no | `false` | `true` writes the value without encoding. |
Returns: `String` The value or the text.
Example: Default text
```js
console.log(Tangular.render("{{ name | def('n/a') }}", { name: null })); // n/a
```
### {{ value | empty([text], [raw]) }}
Type: `method`
Writes a default text for an empty value.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `text` | `String` | no | `DEF.empty` | The text for an empty value. |
| `raw` | `Boolean` | no | `false` | `true` writes the value without encoding. |
Returns: `String` The value or the text.
Every falsy value is empty, including `0`. Other values are encoded unless `raw` is `true`. Passing `true` as the first argument also turns on `raw`.
Example: Empty values
```js
console.log(Tangular.render('{{ name | empty }}', { name: '' })); // ---
console.log(Tangular.render("{{ name | empty('n/a') }}", { name: '' })); // n/a
console.log(Tangular.render('{{ name | empty }}', { name: '' })); // <b>
console.log(Tangular.render('{{ name | empty(true) }}', { name: '' })); //
```
### {{ value | encode([type]) }}
Type: `method`
Encodes a value for output.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | no | | `json` for JSON, `json2` for indented JSON, `url` or `urlencoded` for `encodeURIComponent()`, and `querify` for a query string. |
Returns: `String` The encoded value.
Without `type`, the helper escapes `<`, `>`, `&` and `"`, and writes an empty string for `null` and `undefined`.
Example: Encoding
```js
console.log(Tangular.render('{{ value | encode }}', { value: '' })); // <b>
console.log(Tangular.render("{{ value | encode('json') }}", { value: { a: 1 } })); // {"a":1}
console.log(Tangular.render("{{ value | encode('url') }}", { value: 'a b' })); // a%20b
console.log(Tangular.render("{{ value | encode('querify') }}", { value: { a: 1, b: 'x y' } })); // ?a=1&b=x%20y
```
### {{ value | format([format], [separator], [decimalSeparator]) }}
Type: `method`
Formats a number or a date.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `format` | `Number or String` | no | | The decimal places for a number, or the layout for a date. |
| `separator` | `String` | no | | The thousands separator of a number. |
| `decimalSeparator` | `String` | no | | The decimal separator of a number. |
Returns: `String` The formatted value.
For a number, the arguments are those of [format()](../number/), and a number without `decimals` is written without its decimal part. For a `Date`, the first argument is the layout of [format()](../date/).
A string that holds a date is converted first and uses `dd.MM.yyyy` by default, and a string that holds a number is converted to a number. `null` and `undefined` write an empty string.
Example: Numbers
```js
console.log(Tangular.render('{{ value | format(2) }}', { value: 1234.5 })); // 1 234.50
console.log(Tangular.render("{{ value | format(2, ',', '.') }}", { value: 1234.5 })); // 1,234.50
console.log(Tangular.render('{{ value | format }}', { value: 1234.5 })); // 1 234
```
Example: Dates
```js
var date = new Date(2026, 10, 8, 15, 4);
console.log(Tangular.render("{{ value | format('dd.MM.yyyy HH:mm') }}", { value: date })); // 08.11.2026 15:04
console.log(Tangular.render('{{ value | format }}', { value: '2026-11-08' })); // 08.11.2026
```
### {{ value | pluralize(zero, one, few, other) }}
Type: `method`
Selects the text that matches a number.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `zero` | `String` | yes | | The text for 0. |
| `one` | `String` | yes | | The text for 1. |
| `few` | `String` | yes | | The text for numbers from 2 to 4. |
| `other` | `String` | yes | | The text for other numbers. |
Returns: `String` The selected text.
The arguments are those of [pluralize()](../number/). A numeric string is converted to a number, and an empty value counts as `0`.
Example: Counting items
```js
var template = "{{ count | pluralize('no items', '# item', '# items', '# items') }}";
console.log(Tangular.render(template, { count: 3 })); // 3 items
console.log(Tangular.render(template, { count: 1 })); // 1 item
console.log(Tangular.render(template, { count: null })); // no items
```
### {{ value | raw }}
Type: `method`
Writes a value without encoding.
Returns: `Object` The unchanged value.
Use it only for content that is safe to insert as HTML.
Example: Writing HTML
```js
console.log(Tangular.render('{{ value | raw }}', { value: 'Hi ' })); // Hi
console.log(Tangular.render('{{ value }}', { value: 'Hi ' })); // <b>Hi</b>
```
---
title: Routing
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/routing/
updated: 2026-11-18T17:06:08.115Z
---
# Routing
> The client-side routing API: ROUTE(), REDIRECT(), MIDDLEWARE(), the NAV object, and the route options and events.
These functions map URLs to functions in a single-page application, and `NAV` holds the current state of the navigation. For an introduction with complete examples, read [Routing](../../guides/routing/).
## API
### ROUTE(url, callback, [middleware], [init])
Type: `method`
Registers a function for a URL.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes | | The URL of the route. It can contain dynamic segments such as `{id}` and environment variables such as `[name]`. The value of `DEF.root` is added in front of it. |
| `callback` | `Function` | yes | | The function to run. It receives the values of the dynamic segments. |
| `middleware` | `String or Array` | no | | A comma-separated string or an array of [middleware names](#middleware-name), [roles](#role), [code lists](#code-list) and an [options object](#options-object). The options object is accepted only in an array. |
| `init` | `Function` | no | | A function that runs once, on the first visit, ahead of the middleware. It receives `next`, which must be called to continue. |
Returns: `Object` The `NAV` object, so calls can be chained.
The route for the current URL runs when the application starts. Inside the callback, `this` is `NAV`, and the values of the [dynamic segments](#dynamic-segment) are the arguments.
The URL is compared in lowercase, so write fixed segments in lowercase. A missing trailing slash is added to the address. A static route wins over a dynamic one with the same number of segments, and registering the same URL again replaces the route.
The arguments can also be passed in these orders:
- `ROUTE(url, middleware, callback, [init])`, with `middleware` as an array
- `ROUTE(url, callback, init, [middleware])`
When the current URL is in the 404 state, a route registered for it runs immediately.
Example: Static and dynamic routes
```js
ROUTE('/products/new/', function() {
console.log('form');
});
ROUTE('/products/{id}/', function(id) {
console.log('detail', id, this.url);
});
REDIRECT('/products/new/');
REDIRECT('/products/AB-15');
// Output:
// form
// detail AB-15 /products/AB-15/
```
Example: Prepare a route once
```js
ROUTE('/reports/', function() {
console.log('reports');
}, function(next) {
console.log('prepare once');
next();
});
REDIRECT('/reports/');
REDIRECT('/');
REDIRECT('/reports/');
// Output:
// prepare once
// reports
// reports
```
### REDIRECT([url])
Type: `method`
Navigates to a URL without reloading the page.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no | | The target URL with an optional query string. It can contain environment variables such as `[name]`, and the value of `DEF.root` is added in front of it. The default value is the current URL. |
Without a URL, the current route runs again. `REDIRECT('./')` does the same, `REDIRECT('../')` goes one segment up, and `REDIRECT('../../')` goes two segments up. A query string can follow the dots, for example `REDIRECT('../?page=2')`.
A word starting with `@` at the end of the URL is a [custom flag](#custom-flag).
Example: Navigate
```js
ROUTE('/users/{id}/', function(id) {
console.log('user', id, NAV.query.tab);
});
REDIRECT('/users/15/?tab=orders');
// Output:
// user 15 orders
```
Example: Go one level up
```js
ROUTE('/users/', function() {
console.log('list');
});
ROUTE('/users/{id}/', function(id) {
console.log('user', id);
});
REDIRECT('/users/15/');
REDIRECT('../');
console.log(NAV.url);
// Output:
// user 15
// list
// /users/
```
### MIDDLEWARE(name, callback)
Type: `method`
Registers a named middleware, or runs a list of middleware.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String or Array` | yes | | The name of the middleware, or an array of names to run. |
| `callback` | `Function` | yes | | The middleware. With an array of names, the function to call at the end. |
Returns: `Object` The `NAV` object, so calls can be chained.
A middleware runs ahead of the route callback and decides if the route continues. Inside the callback, `this` is `NAV`. The callback receives:
| Argument | Type | Description |
| --- | --- | --- |
| `next` | Function | `next()` continues. `next(false)` and `next(new Error())` stop the route. |
| `options` | Object | The [options object](#options-object) of the route. |
| `roles` | Array | The [roles](#role) of the route. |
| `route` | Object | The [route object](#route-object). |
The chain stops as well when the URL changes while a middleware is working.
With an array of names, `MIDDLEWARE(names, callback)` runs those middleware one after another and then calls `callback`. Each middleware receives only `next`, and unknown names are skipped.
Example: Protect a route
```js
var user = null;
MIDDLEWARE('auth', function(next, options, roles, route) {
console.log('auth', route.id);
next(user ? undefined : false);
});
ROUTE('/admin/', function() {
console.log('admin page');
}, 'auth');
REDIRECT('/admin/');
setTimeout(function() {
user = { name: 'Ann' };
REDIRECT('/admin/');
}, 100);
// Output:
// auth /admin/
// auth /admin/
// admin page
```
Example: Run a list of middleware
```js
MIDDLEWARE('first', function(next) {
console.log('first');
next();
});
MIDDLEWARE('second', function(next) {
console.log('second');
next();
});
MIDDLEWARE(['first', 'second'], function() {
console.log('done');
});
// Output:
// first
// second
// done
```
### ROUTE('/items/{name}/', callback)
Type: `config`
A dynamic segment of a route URL.
A segment in curly brackets matches any value of that segment. The values are passed to the callback in order and are available in `NAV.params`. They keep their original case. The address must have the same number of segments as the route.
Example: Read two segments
```js
ROUTE('/items/{id}/{tab}/', function(id, tab) {
console.log(id, tab, JSON.stringify(NAV.params));
});
REDIRECT('/items/AB-1/Photos/');
// Output:
// AB-1 Photos ["AB-1","Photos"]
```
### ROUTE(url, callback, 'name')
Type: `config`
Runs a registered middleware for the route.
A plain name in the `middleware` argument of `ROUTE()` selects a middleware registered with [MIDDLEWARE()](#middleware). The middleware run in the listed order, and a name that is not registered is skipped.
Example: Two middleware
```js
MIDDLEWARE('first', function(next) {
console.log('first');
next();
});
MIDDLEWARE('second', function(next) {
console.log('second');
next();
});
ROUTE('/orders/', function() {
console.log('orders');
}, 'first,second');
REDIRECT('/orders/');
// Output:
// first
// second
// orders
```
### ROUTE(url, callback, ['name', '@role'])
Type: `config`
Adds a role that middleware receive in the roles array.
An item starting with `@` is passed to every middleware of the route in the `roles` array, without the `@`. Roles have no effect of their own: the middleware decides what they mean.
Example: Read the roles
```js
MIDDLEWARE('auth', function(next, options, roles) {
console.log(roles.join());
next();
});
ROUTE('/admin/', function() {
console.log('admin page');
}, ['auth', '@admin', '@editor']);
REDIRECT('/admin/');
// Output:
// admin,editor
// admin page
```
### ROUTE(url, callback, '#name')
Type: `config`
Loads a code list ahead of the route callback.
An item starting with `#` loads the code list with that name through `CL()`, in its position in the middleware chain. See [Global functions](../globals/).
Example: Load a code list
```js
CLINIT('countries', function(next) {
console.log('loading countries');
next([{ id: 'sk', name: 'Slovakia' }]);
});
ROUTE('/orders/', function() {
console.log('orders', DEF.cl.countries.length);
}, '#countries');
REDIRECT('/orders/');
// Output:
// loading countries
// orders 1
```
### ROUTE(url, callback, ['name', { key: value }])
Type: `config`
Passes options to the middleware of the route.
An object in the middleware array is passed to every middleware of the route as `options`. It is also available in `options` of the [route object](#route-object).
Example: Read the options
```js
MIDDLEWARE('layout', function(next, options) {
console.log(options.title);
next();
});
ROUTE('/admin/', function() {
console.log('admin page');
}, ['layout', { title: 'Administration' }]);
REDIRECT('/admin/');
// Output:
// Administration
// admin page
```
### REDIRECT('/url/ @name')
Type: `config`
Emits a flag event when navigating.
A word starting with `@` is removed from the URL, and the event `@flag name` is emitted ahead of the navigation. See [Events](../events/).
Example: React to a flag
```js
ON('@flag audit', function() {
console.log('audit');
});
ROUTE('/orders/', function() {
console.log(NAV.url);
});
REDIRECT('/orders/ @audit');
// Output:
// audit
// /orders/
```
### NAV.routes[index]
Type: `type`
Describes one registered route.
Middleware receive this object as the `route` argument, and `NAV.routes` contains one for each route.
| Property | Type | Description |
| --- | --- | --- |
| `id` | String | The URL of the route. |
| `url` | Array | The segments of the URL. |
| `fn` | Function | The route callback. |
| `priority` | Number | The position in the matching order. A higher number is tried first. |
| `params` | Array | The indexes of the dynamic segments. |
| `middleware` | Array | The middleware names and code lists, or `null`. |
| `init` | Function | The `init` function. It is `null` after it has run. |
| `count` | Number | How many times the route has matched. |
| `pending` | Boolean | `true` while the middleware or `init` are working. |
| `options` | Object | The [options object](#options-object). |
| `roles` | Array | The [roles](#role). |
Example: Inspect a route
```js
ROUTE('/items/{id}/', function() {}, ['auth', '@admin', { title: 'Items' }]);
MIDDLEWARE('auth', function(next) {
next();
});
var route = NAV.routes[0];
console.log(route.id, JSON.stringify(route.url), JSON.stringify(route.params));
console.log(JSON.stringify(route.middleware), JSON.stringify(route.roles), route.options.title);
// Output:
// /items/{id}/ ["items","{id}"] [1]
// ["auth"] ["admin"] Items
```
### NAV.autosave()
Type: `method`
Saves the history to the browser storage at each navigation.
After this call, the history is stored the same way as with [NAV.save()](#nav-save) every time it changes. [NAV.load()](#nav-load) reads it back.
Example: Keep the history
```js
NAV.autosave();
REDIRECT('/a/');
REDIRECT('/b/');
REDIRECT('/c/');
NAV.history.length = 0;
NAV.load();
console.log(JSON.stringify(NAV.history));
// Output:
// ["/a/","/b/"]
```
### NAV.back()
Type: `method`
Goes to the previous URL.
Returns: `Object` The `NAV` object, so calls can be chained.
With an empty history, it goes to `/`.
Example: Go back
```js
REDIRECT('/a/');
REDIRECT('/b/');
NAV.back();
console.log(NAV.url, NAV.next());
// Output:
// /a/ /b/
```
### NAV.clientside(selector)
Type: `method`
Turns matching elements into client-side links.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `selector` | `String` | yes | | A jQuery selector of the links. |
Returns: `Object` The `NAV` object, so calls can be chained.
A click on a matching element navigates with `REDIRECT()`. The URL is read from `href`, `data-href` or `data-url`. The values `#` and `javascript:void(0)` are ignored. Elements added later work too.
Example: Links
```html
About
Contact
```
### NAV.custom()
Type: `method`
Keeps the navigation inside the application.
Routes and `REDIRECT()` work as usual, and the address bar stays as it is. This suits an application embedded in another page. Call it at the start of the application.
Example: Navigate inside the application
```js
NAV.custom();
ROUTE('/inbox/', function() {
console.log('inbox', NAV.url);
});
REDIRECT('/inbox/');
// Output:
// inbox /inbox/
```
### NAV.forward()
Type: `method`
Goes to the next URL after going back.
Returns: `Object` The `NAV` object, so calls can be chained.
When there is no next URL, it goes to `/`.
Example: Go forward
```js
REDIRECT('/a/');
REDIRECT('/b/');
NAV.back();
NAV.forward();
console.log(NAV.url);
// Output:
// /b/
```
### NAV.load()
Type: `method`
Restores the history from the browser storage.
It reads what [NAV.save()](#nav-save) or [NAV.autosave()](#nav-autosave) stored. The next navigation does not add the current URL to the restored history.
Example: Restore the history
```js
REDIRECT('/a/');
REDIRECT('/b/');
NAV.save();
NAV.history.length = 0;
NAV.load();
console.log(JSON.stringify(NAV.history));
// Output:
// ["/a/"]
```
### NAV.location(url, [skiphistory])
Type: `method`
Runs the route of a URL without changing the address bar.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes | | The URL to process. |
| `skiphistory` | `Boolean` | no | `false` | `true` does not add the current URL to the history. |
`NAV` is updated, the events are emitted and the route runs, like in `REDIRECT()`. The address in the browser is not changed.
Example: Process URLs
```js
ROUTE('/a/', function() {
console.log('a');
});
NAV.location('/a/');
NAV.location('/b/');
NAV.location('/c/', true);
console.log(NAV.url, JSON.stringify(NAV.history));
// Output:
// a
// /c/ ["/a/"]
```
### NAV.next()
Type: `method`
Returns the URL that NAV.forward() opens.
Returns: `String` The next URL, or `undefined` when there is none.
Example: Read the next URL
```js
REDIRECT('/a/');
REDIRECT('/b/');
NAV.back();
console.log(NAV.next());
// Output:
// /b/
```
### NAV.path(url, [delimiter])
Type: `method`
Adds the trailing delimiter to a URL.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes | | The URL. |
| `delimiter` | `String` | no | `'/'` | The character to add. |
Returns: `String` The URL with the delimiter.
A query string is kept after the delimiter. A URL starting with `#` is returned unchanged.
Example: Normalize URLs
```js
console.log(NAV.path('/products'));
console.log(NAV.path('/products?page=2'));
console.log(NAV.path('#inbox'));
// Output:
// /products/
// /products/?page=2
// #inbox
```
### NAV.prev()
Type: `method`
Returns the URL that NAV.back() opens.
Returns: `String` The previous URL, or `undefined` when there is none.
Example: Read the previous URL
```js
REDIRECT('/a/');
REDIRECT('/b/');
console.log(NAV.prev());
// Output:
// /a/
```
### NAV.redirect([url])
Type: `method`
The same function as REDIRECT().
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | no | | The target URL. The default value is the current URL. |
See [REDIRECT()](#redirect).
Example: Navigate
```js
ROUTE('/a/', function() {
console.log('a');
});
NAV.redirect('/a/');
// Output:
// a
```
### NAV.refresh()
Type: `method`
Runs the route of the current URL again.
The history does not change.
Example: Run the route again
```js
ROUTE('/a/', function() {
console.log('a');
});
REDIRECT('/a/');
NAV.refresh();
console.log(JSON.stringify(NAV.history));
// Output:
// a
// a
// []
```
### NAV.reload()
Type: `method`
The same as NAV.refresh().
See [NAV.refresh()](#nav-refresh).
Example: Run the route again
```js
ROUTE('/a/', function() {
console.log('a');
});
REDIRECT('/a/');
NAV.reload();
// Output:
// a
// a
```
### NAV.remember(name, [value])
Type: `method`
Adds a query parameter to every following REDIRECT().
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes | | The name of the query parameter. |
| `value` | `String` | no | | The value, or `null` to stop. |
Without a value, the current value of the parameter in `NAV.query` is kept. The value `null` stops adding the parameter.
Example: Keep a parameter
```js
NAV.remember('lang', 'de');
REDIRECT('/list/');
console.log(NAV.href);
NAV.remember('lang', null);
REDIRECT('/list/');
console.log(NAV.href);
// Output:
// /list/?lang=de
// /list/
```
### NAV.remove(url)
Type: `method`
Removes a route.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes | | The URL used in `ROUTE()`. |
Returns: `Object` The `NAV` object, so calls can be chained.
Example: Remove a route
```js
ROUTE('/a/', function() {
console.log('a');
});
NAV.remove('/a/');
REDIRECT('/a/');
console.log(NAV.is404);
// Output:
// true
```
### NAV.save()
Type: `method`
Stores the history in the browser storage once.
The previous and next URLs are written to `localStorage` under the key `DEF.localstorage + '.nav'`.
Example: Store the history
```js
REDIRECT('/a/');
REDIRECT('/b/');
NAV.save();
var data = JSON.parse(localStorage.getItem(DEF.localstorage + '.nav'));
console.log(JSON.stringify(data.prev));
// Output:
// ["/a/"]
```
### NAV.status(code, [data])
Type: `method`
Emits an event named after a code.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `code` | `Number or String` | yes | | The name of the event. |
| `data` | `Object` | no | | The argument of the event. |
Returns: `Object` The `NAV` object, so calls can be chained.
This gives an application one place to handle errors.
Example: Report an error
```js
ON('500', function(error) {
console.log('failed:', error);
});
NAV.status(500, 'Database is down');
// Output:
// failed: Database is down
```
### NAV.hashtags
Type: `property`
Drives the routes with the hash part of the URL.
Returns: `Boolean` The default value is `false`.
Set it to `true` at the start of the application. Write the routes with a leading `#`, and navigate with links or `location.hash`.
Example: Routes on the hash
```js
NAV.hashtags = true;
ROUTE('#inbox', function() {
console.log('inbox', NAV.url);
});
setTimeout(function() {
location.hash = '#inbox';
}, 100);
// Output:
// inbox #inbox
```
### NAV.href
Type: `property`
The URL passed to the last navigation.
Returns: `String` The URL with its query string.
Example: Read the URL
```js
REDIRECT('/search/?q=lamp');
console.log(NAV.href);
// Output:
// /search/?q=lamp
```
### NAV.history
Type: `property`
The previous URLs.
Returns: `Array` An array of strings.
The items are paths without the query string. The last item is the most recent one.
Example: List the previous URLs
```js
REDIRECT('/a/?page=2');
REDIRECT('/b/');
REDIRECT('/c/');
console.log(JSON.stringify(NAV.history));
// Output:
// ["/a/","/b/"]
```
### NAV.is404
Type: `property`
Tells if no route matches the current URL.
Returns: `Boolean` `true` when no route matches.
Example: Check the state
```js
ROUTE('/a/', function() {});
REDIRECT('/missing/');
console.log(NAV.is404);
REDIRECT('/a/');
console.log(NAV.is404);
// Output:
// true
// false
```
### NAV.isback
Type: `property`
The number of URLs to go back to.
Returns: `Number` The number of previous URLs.
It is a path, so the markup can bind to it.
Example: Count the previous URLs
```js
REDIRECT('/a/');
REDIRECT('/b/');
REDIRECT('/c/');
console.log(NAV.isback);
// Output:
// 2
```
### NAV.isforward
Type: `property`
The number of URLs to go forward to.
Returns: `Number` The number of next URLs.
It is a path, so the markup can bind to it.
Example: Count the next URLs
```js
REDIRECT('/a/');
REDIRECT('/b/');
NAV.back();
console.log(NAV.isforward);
// Output:
// 1
```
### NAV.middlewares
Type: `property`
The registered middleware.
Returns: `Object` The functions, with the middleware names as keys.
Example: List the names
```js
MIDDLEWARE('auth', function(next) {
next();
});
console.log(Object.keys(NAV.middlewares).join());
// Output:
// auth
```
### NAV.params
Type: `property`
The values of the dynamic segments of the current route.
Returns: `Array` An array of strings.
It is a path, so the markup can bind to it.
Example: Read the values
```js
ROUTE('/items/{id}/{tab}/', function() {
console.log(JSON.stringify(NAV.params));
});
REDIRECT('/items/15/photos/');
// Output:
// ["15","photos"]
```
### NAV.query
Type: `property`
The parsed query string of the current URL.
Returns: `Object` The parameters. All values are strings.
The names and values are decoded, and a `+` becomes a space. It is a path, so the markup can bind to it.
Example: Read the query string
```js
REDIRECT('/search/?q=desk+lamp&page=2');
console.log(JSON.stringify(NAV.query));
// Output:
// {"q":"desk lamp","page":"2"}
```
### NAV.queryraw
Type: `property`
The query string as text.
Returns: `String` The query string without the leading `?`.
Example: Read the text
```js
REDIRECT('/search/?q=lamp&page=2');
console.log(NAV.queryraw);
// Output:
// q=lamp&page=2
```
### NAV.routes
Type: `property`
The registered routes.
Returns: `Array` An array of route objects.
The array is sorted in the matching order. Each item is a [route object](#route-object).
Example: List the routes
```js
ROUTE('/items/{id}/', function() {});
ROUTE('/items/new/', function() {});
console.log(NAV.routes.map(route => route.id).join());
// Output:
// /items/new/,/items/{id}/
```
### NAV.ua
Type: `property`
Information about the browser.
Returns: `Object` The object of `MAIN.ua`.
It is the same object as `MAIN.ua` and is available when the application has started. See [MAIN](../main/).
Example: Compare with MAIN
```js
ROUTE('/', function() {
console.log(NAV.ua === MAIN.ua);
});
// Output:
// true
```
### NAV.url
Type: `property`
The current path without the query string.
Returns: `String` The path with a trailing slash.
It is a path, so the markup can bind to it with ` `.
Example: Read the path
```js
REDIRECT('/search?q=lamp');
console.log(NAV.url);
// Output:
// /search/
```
### ON('location', function(url) {})
Type: `event`
Emitted when the URL changes, ahead of the route callback.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes | | The path without the query string. |
Example: Watch the navigation
```js
ON('location', function(url) {
console.log('location', url);
});
ROUTE('/a/', function() {
console.log('route');
});
REDIRECT('/a/?page=2');
// Output:
// location /a/
// route
```
### ON('404', function() {})
Type: `event`
Emitted when no route matches the URL.
Example: Handle an unknown URL
```js
ON('404', function() {
console.log('not found', NAV.url);
});
REDIRECT('/missing/');
// Output:
// not found /missing/
```
### ON('route', function(url) {})
Type: `event`
Emitted when a route is registered.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes | | The URL of the route. |
Example: Watch the registration
```js
ON('route', function(url) {
console.log('registered', url);
});
ROUTE('/a/', function() {});
// Output:
// registered /a/
```
---
title: String
project: jComponent V20
version: 20.015
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v20/20-015/reference/string/
updated: 2026-11-18T13:58:19.462Z
---
# String
> Methods that jComponent adds to String.prototype for formatting, parsing, validating and cleaning text.
jComponent adds these methods to every string. Number and date output follows the settings in [DEF](../def/), values in `[key]` form come from [ENV()](../globals/), and the methods that read component configuration are used in [Creating components](../../guides/creating-components/).
## API
### String.args(obj, [encode])
Type: `method`
Replaces `{key}` and `{{ key }}` placeholders with values from an object.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes | | The values for the placeholders. |
| `encode` | `String or Function` | no | | How to write each value: `json` for `JSON.stringify()`, `encode` for `encodeURIComponent()`, `escape` for HTML entities, or a function `(value, key)` that returns the text. |
Returns: `String` The string with the placeholders replaced.
A key can be a nested path such as `user.age`. Without `encode`, a key that is not in the object keeps its placeholder and a `null` value becomes an empty string.
Example: Placeholders
```js
console.log('Hello {name}, age {{ user.age }}, {unknown}'.args({ name: 'Ana', user: { age: 30 } })); // Hello Ana, age 30, {unknown}
```
Example: Encoding the values
```js
console.log('{a}'.args({ a: '' }, 'escape')); // <b>
console.log('{a}'.args({ a: 'x y' }, 'encode')); // x%20y
console.log('{a}'.args({ a: 'x' }, 'json')); // "x"
console.log('{a}|{b}'.args({ a: 1, b: 2 }, (value, key) => key + '=' + value)); // a=1|b=2
```
### String.encode()
Type: `method`
Escapes the characters `<`, `>`, `&` and `"` as HTML entities.
Returns: `String` The escaped text.
Example: Escaping HTML
```js
console.log('T&C '.encode()); // <a href="x">T&C</a>
```
### String.env()
Type: `method`
Replaces `[key]` phrases with values from the environment.
Returns: `String` The string with the known phrases replaced.
A `[key]` phrase reads the value set with [ENV()](../globals/). A phrase that starts with a dot, such as `[.app.name]`, reads a path from `window`. A phrase with no value stays in the text.
Example: Environment values
```js
ENV('name', 'Peter');
window.app = { version: 5 };
console.log('[name] [.app.version] [missing]'.env()); // Peter 5 [missing]
```
### String.flags([path])
Type: `method`
Removes `@name` flags from the text and emits an event for each flag that has a listener.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | no | | The value passed to the event listeners. |
Returns: `String` The trimmed text without the flags.
Each flag emits the event `@flag name` with `path` as its argument. See [Flags and path modifiers](../../guides/flags/).
Example: Reading flags
```js
var seen = [];
ON('@flag reset', path => seen.push(path));
console.log('form.name @reset @other'.flags('form.name')); // form.name
console.log(seen); // ["form.name"]
```
### String.format([value0], [value1], [...])
Type: `method`
Replaces the indexes `{0}`, `{1}` and so on with the arguments.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value0` | `Object` | no | | The value for `{0}`. Each further argument fills the next index. |
Returns: `String` The formatted text.
An array argument is joined without a separator. A missing or `null` argument becomes an empty string.
Example: Indexed values
```js
console.log('Hello {0}, you have {1} items{2}'.format('Ana', 3)); // Hello Ana, you have 3 items
console.log('{0}'.format(['a', 'b'])); // ab
```
### String.isEmail()
Type: `method`
Checks that the string is an email address.
Returns: `Boolean` `true` for a valid address.
The test uses the pattern in `DEF.regexp.email`.
Example: Checking addresses
```js
console.log('peter+news@total-js.com'.isEmail()); // true
console.log('a@b'.isEmail()); // false
```
### String.isJSONDate()
Type: `method`
Checks that the string is a date serialized to JSON.
Returns: `Boolean` `true` for a value in the form `2026-11-18T10:00:00.000Z`.
Example: Checking dates
```js
console.log('2026-11-18T10:00:00.000Z'.isJSONDate()); // true
console.log('2026-11-18'.isJSONDate()); // false
```
### String.isPhone()
Type: `method`
Checks that the string is a phone number.
Returns: `Boolean` `true` for a valid number.
The test uses the pattern in `DEF.regexp.phone`: an optional `+`, then groups of three, three and four to eight digits. The groups can be separated by a space, a dash or a dot, and the first can be in parentheses.
Example: Checking numbers
```js
console.log('+421903123456'.isPhone()); // true
console.log('(421) 903-1234'.isPhone()); // true
console.log('12345'.isPhone()); // false
```
### String.isURL()
Type: `method`
Checks that the string is an `http` or `https` address.
Returns: `Boolean` `true` for a valid address.
The test uses the pattern in `DEF.regexp.url`.
Example: Checking addresses
```js
console.log('https://www.totaljs.com/'.isURL()); // true
console.log('ftp://totaljs.com/file'.isURL()); // false
console.log('totaljs.com'.isURL()); // false
```
### String.padLeft(length, [char])
Type: `method`
Fills the start of the string up to a length.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | yes | | The final length. |
| `char` | `String` | no | `a space` | The fill character. |
Returns: `String` The padded text.
A string that is already long enough is returned unchanged.
Example: Padding
```js
console.log('7'.padLeft(3, '0')); // 007
console.log('abcd'.padLeft(2, '0')); // abcd
```
### String.padRight(length, [char])
Type: `method`
Fills the end of the string up to a length.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `length` | `Number` | yes | | The final length. |
| `char` | `String` | no | `a space` | The fill character. |
Returns: `String` The padded text.
A string that is already long enough is returned unchanged.
Example: Padding
```js
console.log('7'.padRight(3, '-')); // 7--
```
### String.parseComponent(tags)
Type: `method`
Extracts the content of HTML tags from a string.
| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `tags` | `Object` | yes | | The result keys and their opening tags. |
Returns: `Object` The content found for each key.
Each key of `tags` holds the exact opening tag to look for. Nested tags of the same name stay in the content. A tag that is not found is left out of the result.
Example: Splitting a template
```js
var html = '';
console.log(html.parseComponent({ css: '