Spanish Total.js
English
Documentation For AI agents
Contents

Global functions

The functions and variables that the library adds to the window object.

.md GitHub
On this page

The library adds these functions and variables to window, so they are available everywhere in your code. Start with Paths and Data binding to see how they work together.

API

method

ADAPT(path, id, text)

Prepares a piece of HTML for a specific path and identifier.
ParameterTypeDescription
path String The value for ~PATH~ and CLASS. Use null to skip these replacements.
id String The value for ~ID~. Use null to skip this replacement.
text String The text to prepare.

Returns String The prepared text.

The method translates @(text) markup, applies --name-- variables and replaces ~CDN~ with DEF.cdn. When path is set, ~PATH~ and CLASS become the path, <ui-plugin> 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.

Replace the keywords
var html = '<div class="CLASS" data-id="~ID~">~PATH~</div>';
console.log(ADAPT('users', 'u1', html)); // <div class="users" data-id="u1">users</div>
method

AJAX(url, [data], callback, [onprogress], [scope], [id])

Sends an HTTP request and delivers the response to a function or a path.
ParameterTypeDescription
url String The method, the address and optional keywords, for example POST /api/users/ ERROR.
data? Object The request body: an object sent as JSON, a string sent as form data, or FormData.
callback Function|String A function that receives the response, or a path that receives it.
onprogress? Function|String A function or a path that receives the upload percentage.
scope? Object The object in which a callback path is resolved. Default: window
id? String The key used by SYNC and by the cache. Default: url

The url starts with the HTTP method, followed by the address and optional keywords separated by spaces:

KeywordMeaning
ERRORPasses the response through ERROR(). 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.
SYNCQueues requests with the same id, so that they run one after another.
<1 minute>Caches the response for the given time with CACHE(), 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.
#nameLoads the code list name first. See CL().
@flagEmits the flag when the request is sent. See Flags and path modifiers.

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(). Every request adds the headers from DEF.headers. When DEF.language is set, it is added to the query string. When DEF.version is set, it is added to the query string of .html addresses.

The request and response 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.

Read a response
AJAX('GET /api/users/', function(response) {
	console.log(response.length); // 2
});
Store a response in a path
AJAX('POST /api/orders/', { amount: 10 }, 'orders.last');

WATCH('orders.last', function(value) {
	console.log(value.id); // 100
});
Send form data
AJAX('POST /api/login/', 'name=Ann&remember=1', function(response) {
	console.log(response.ok); // true
});
Stop a request
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();
method

API(url, name, [data], callback, [scope])

Calls a Total.js API endpoint on a specific address.
ParameterTypeDescription
url String The address of the endpoint.
name String The name of the operation, optionally followed by keywords.
data? Object The data of the operation.
callback Function|String A function or a path that receives the response.
scope? Object The object in which a callback path is resolved. Default: window

The method sends POST url with the JSON body { schema: name, data: data }. Keywords accepted by AJAX() can follow the name, for example users_list ERROR. To use one fixed address, see TAPI() and PIPE().

Call an operation
API('/admin/api/', 'users_read', { id: 5 }, function(response) {
	console.log(response.name); // Peter
});
method

APPEARANCE(options)

Sets the colour scheme of the page through CSS variables and body classes.
ParameterTypeDescription
options Object 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 and adds the variable --rgb with the red, green and blue values of a hexadecimal colour with three or six digits.

KeyMeaning
dark or darkmodeToggles the class ui-dark on the body.
large or largemodeToggles the class ui-large on the body.

The class prefix comes from DEF.prefixcsslibrary.

Dark theme with an accent colour
APPEARANCE({ dark: true, color: '#4285F4' });

console.log($('#cssappearance').html()); // :root{--color:#4285F4;--rgb:66,133,244}
console.log($('body').hclass('ui-dark')); // true
A short colour
APPEARANCE({ color: '#abc' });

console.log($('#cssappearance').html()); // :root{--color:#abc;--rgb:170,187,204}
method

ASETTER(name, [a], [b], [c], [d])

Creates a function that calls a component method later.
ParameterTypeDescription
name String The selector and the method, in the same form as in SETTER().
a? Object The first argument.
b? Object The second argument.
c? Object The third argument.
d? Object The fourth argument.

Returns Function A function without arguments.

Each call of the returned function runs SETTER() with the arguments given here.

Prepare a call
<ui-component name="counter"></ui-component>

<script>
COMPONENT('counter', function(self) {
	self.add = function(value) {
		console.log('added', value); // added 5
	};
});

ON('ready', function() {
	var add = ASETTER('counter/add', 5);
	add();
});
</script>
method

ATTRD(element, [name])

Reads a data-* attribute from an element or from its closest parent that has it.
ParameterTypeDescription
element jQuery|Event|Element|Object The starting point.
name? String The attribute name without the data- prefix. Default: id

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.

Read the closest identifier
<div data-id="15" data-type="user"><button id="save">Save</button></div>

<script>
var button = $('#save');
console.log(ATTRD(button)); // 15
console.log(ATTRD(button, 'type')); // user
console.log(ATTRD({ id: 20 })); // 20
</script>
method

BLOCKED(key, timeout, [callback])

Limits how often an operation can run.
ParameterTypeDescription
key String The name of the operation.
timeout Number|String The time in milliseconds, or a text such as 5 minutes.
callback? Function 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.

Allow one click per second
ON('ready', function() {
	console.log(BLOCKED('save', 1000)); // false
	console.log(BLOCKED('save', 1000)); // true
});
method

CACHE(key, [value], [expire])

Reads or writes a value in the persistent cache.
ParameterTypeDescription
key String The key.
value? Object The value to store.
expire? String 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.

The cache is loaded when the library starts, so use it from the ready event onward.

Write and read
ON('ready', function() {
	CACHE('filter', { page: 2 }, '1 day');
	console.log(CACHE('filter')); // {"page":2}
	console.log(CACHE('missing')); // null
});
method

CACHEPATH(path, expire, [def])

Keeps the value of a path in the cache between visits.
ParameterTypeDescription
path String The path.
expire String The lifetime of the saved value, for example 1 day.
def? Object|Function The value used when nothing is saved. A function is called to get it.

The method saves every change of the path with CACHE() 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().

Remember a filter
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
method

CL(name, [callback])

Loads code lists registered with CLINIT().
ParameterTypeDescription
name String One name, or several names separated by commas.
callback? Function 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. 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.

Load a list on demand
CLINIT('countries', function(next) {
	next([{ id: 'SK', name: 'Slovakia' }]);
});

ON('ready', function() {
	CL('countries', function() {
		console.log(DEF.cl.countries.length); // 1
	});
});
method

clearTimeout2(name)

Cancels a timer created with setTimeout2().
ParameterTypeDescription
name String The name of the timer.

Returns Boolean true when the timer exists.

Cancel a timer
setTimeout2('search', NOOP, 1000);
console.log(clearTimeout2('search')); // true
console.log(clearTimeout2('unknown')); // false
method

CLINIT(name, source, [init])

Registers the source of a code list.
ParameterTypeDescription
name String The name of the code list.
source Function|String A function, a request or an operation.
init? Boolean Loads the list immediately. Default: false

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(). Any other value is an operation for TAPI().

Load several lists at once
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);
});
method

CLONE(value, [raw])

Creates a deep copy of a value.
ParameterTypeDescription
value Object|String The value to copy, or a path.
raw? Boolean Treats a string as a plain value. Default: false

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.

Copy an object
var a = { user: { name: 'Peter' } };
var b = CLONE(a);
b.user.name = 'Lucia';
console.log(a.user.name); // Peter
Copy the value of a path
SET('form', { name: 'Peter' });
var copy = CLONE('form');
console.log(copy); // {"name":"Peter"}
method

CLRELOAD(name, [callback])

Loads code lists again from their sources.
ParameterTypeDescription
name String One name, or several names separated by commas.
callback? Function A function that runs when the lists are reloaded.

Only lists that are already loaded are reloaded. Other names are skipped.

Refresh a list
var counter = 0;

CLINIT('stats', function(next) {
	next([++counter]);
});

ON('ready', function() {
	CL('stats', function() {
		CLRELOAD('stats', function() {
			console.log(DEF.cl.stats); // [2]
		});
	});
});
method

CMD(name, [a], [b], [c], [d])

Runs a command on every component that registers it.
ParameterTypeDescription
name String The command, optionally followed by flags.
a? Object The first argument.
b? Object The second argument.
c? Object The third argument.
d? Object The fourth argument.

Components register commands with command(). Flags can follow the name after a space, for example CMD('refresh @saved'): they are emitted first, as with SET(). To run a command only in a part of the page, use $(selector).CMD() or plugin.cmd().

Clear every list
<ui-component name="list"></ui-component>
<ui-component name="list"></ui-component>

<script>
var count = 0;

COMPONENT('list', function(self) {
	self.command('clear', value => count += value);
});

ON('ready', function() {
	CMD('clear', 1);
	console.log(count); // 2
});
</script>
method

COMPONENT(name, [config], callback, [dependencies], [css])

Registers a component declaration.
ParameterTypeDescription
name String The name of the component.
config? String The default configuration in the form key:value;key:value.
callback Function The declaration: function(self, config, cls).
dependencies? String|Array Addresses to import first, separated by commas. An array can also contain functions that receive next.
css? String 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 and the Component object.

Declare a component
<ui-component name="hello"></ui-component>

<script>
COMPONENT('hello', 'name:World', function(self, config, cls) {
	self.make = function() {
		self.element.aclass(cls).html('Hello ' + config.name);
		console.log(self.element.html()); // Hello World
	};
});
</script>
method

COMPONENTS(path)

Returns the components bound to a path.
ParameterTypeDescription
path String The path, optionally with flags.

Returns Array The matching 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.

Find the required fields
<ui-component name="field" path="form.name" config="required:true"></ui-component>
<ui-component name="field" path="form.note"></ui-component>

<script>
COMPONENT('field', function(self) {
	self.setter = NOOP;
});

ON('ready', function() {
	console.log(COMPONENTS('form').length); // 2
	console.log(COMPONENTS('form @required').length); // 1
});
</script>
method

CONFIG(selector, config)

Changes the configuration of existing and future components.
ParameterTypeDescription
selector String|Function The components to configure.
config String|Object The configuration, as an object or in the form key:value;key:value.

The selector can be:

SelectorMatches
nameComponents with this name.
#idThe component with this identifier.
.pathComponents whose path contains path.
*All components.
a, bSeveral selectors separated by commas.
function(instance)Components for which the function returns true.
Configure by name
<ui-component name="box"></ui-component>

<script>
COMPONENT('box', function(self) {});

ON('ready', function() {
	CONFIG('box', 'color:red;size:10');
	console.log(FIND('box').config.size); // 10
});
</script>
property

COOKIES

Reads and writes browser cookies.

Returns Object The object with the methods.

The object has three methods:

MethodDescription
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.
Write and read a cookie
COOKIES.set('theme', 'dark', '1 month', 'lax');
console.log(COOKIES.get('theme')); // dark
Keep a cookie for a week
COOKIES.set('token', 'a=1', 7);
console.log(COOKIES.get('token')); // a=1
method

COPY(source, target)

Copies the properties of one object to another.
ParameterTypeDescription
source Object The object to read from.
target Object The object to write to.

Returns Object The target object.

Nested objects are cloned, so later changes in source do not affect target.

Merge two objects
var target = { a: 1 };
COPY({ b: { c: 2 } }, target);
console.log(target); // {"a":1,"b":{"c":2}}
method

CSS(value, [id], [selector])

Another name for STYLE().
ParameterTypeDescription
value String|Array The CSS.
id? String The identifier of the style element.
selector? String A selector that prefixes every rule.

See STYLE(). Setting window.jc_globals = { CSS: false } ahead of the library script leaves this global undefined.

property

DAYS

The English names of the days of the week, starting with Sunday.

Returns Array Seven strings.

Read a day
console.log(DAYS[1]); // Monday
property

DEF

The default settings of the library.

Returns Object The settings.

Described on its own page: DEF.

method

DECRYPT(text, [key], [type])

Reads a value written by ENCRYPT().
ParameterTypeDescription
text String The text from ENCRYPT().
key? String The key.
type? String The prefix of the text.

Returns Object The value, or undefined.

The key and the type must be the ones given to ENCRYPT(). 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.

Read an object back
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
method

DIFFDOM(element, selector, html, [attribute])

Updates the children of an element so that they match new HTML.
ParameterTypeDescription
element jQuery The parent element.
selector String A selector of the compared children.
html String The new content.
attribute? String 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.

Update a list
<ul id="list"><li>A</li><li>B</li></ul>

<script>
var list = $('#list');
var result = DIFFDOM(list, 'li', '<li>A</li><li>C</li>');
console.log(result); // {"add":1,"upd":1,"rem":1}
console.log(list.html()); // <li>A</li><li>C</li>
</script>
method

EMIT(name, [a], [b], [c], [d])

Emits an event.
ParameterTypeDescription
name String The name of the event.
a? Object The first argument.
b? Object The second argument.
c? Object The third argument.
d? Object The fourth argument.

Handlers registered with ON(), and handlers registered on components and plugins, receive the arguments. Flags can follow the name, for example refresh @loading. The events of the library are listed in Events.

Emit a custom event
ON('saved', function(id, name) {
	console.log(id, name); // 5 Peter
});

EMIT('saved', 5, 'Peter');
property

EMPTYARRAY

A frozen empty array.

Returns Array An array that cannot be changed.

A shared default value
console.log(Object.isFrozen(EMPTYARRAY)); // true
property

EMPTYOBJECT

A frozen empty object.

Returns Object An object that cannot be changed.

A shared default value
console.log(Object.isFrozen(EMPTYOBJECT)); // true
method

ENCRYPT(value, [key], [type])

Encodes a value as text with a checksum.
ParameterTypeDescription
value String|Object The value.
key? String The key of the checksum.
type? String A prefix written at the beginning of the text.

Returns String The encoded text.

An object or an array is serialized with STRINGIFY() first. The result has the type as a prefix, the value in hexadecimal digits, the letter x and a checksum made with HASH() 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() find out whether the text was changed.

Encode and decode
var text = ENCRYPT('hello', 'secret');

console.log(text); // 68656c6c6fxds46dr
console.log(DECRYPT(text, 'secret')); // hello
console.log(DECRYPT(text, 'other')); // undefined
method

ENV(name, [value])

Reads or writes environment variables.
ParameterTypeDescription
name String|Object The name, or an object with names and values.
value? Object The value to write.

Returns Object The value of the variable.

Variables are stored in DEF.env. 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.

Use a variable in a text
ENV('api', '/api/v1/');
console.log(ENV('api')); // /api/v1/
console.log('[api]users/'.env()); // /api/v1/users/
method

ENVIRONMENT(name, [version], [language], [env])

Sets the storage key, version, language and environment variables of the app.
ParameterTypeDescription
name String The key used in localStorage.
version? String The version of the app.
language? String The language of the app.
env? Object Environment variables.

The method assigns DEF.localstorage, DEF.version and DEF.language, and passes env to ENV(). Call it directly after the library script, so that the app reads its own storage.

Configure an app
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
method

ERROR(response, [success], [error])

Checks a response for errors and runs the matching handler.
ParameterTypeDescription
response Object The response to check.
success? Function|String Runs when there is no error.
error? Function|String 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.

success and error can be functions, or names for SEEX().

Call ERROR(success, [error]) without a response to create a function that you can pass as a callback.

Check a response
console.log(ERROR({ id: 1 })); // false
console.log(ERROR([{ error: 'Invalid name' }])); // true
Create a callback
var callback = ERROR(function(response) {
	console.log(response.id); // 1
});

callback({ id: 1 });
method

ERRORS(path, callback)

Returns the invalid components of a path or of an element.
ParameterTypeDescription
path String|jQuery A path, or an element that contains the components.
callback Function A function that receives an array of components.
Validate a form
<ui-component name="field" path="form.name" config="required:true"></ui-component>

<script>
COMPONENT('field', function(self) {
	self.validate = function(value) {
		return !!value;
	};
});

ON('ready', function() {
	ERRORS('form', function(components) {
		console.log(components.length); // 1
	});
});
</script>
method

EXEC(name, [a], [b], [c], [d])

Calls a function by its name.
ParameterTypeDescription
name String The target of the call.
a? Object The first argument.
b? Object The second argument.
c? Object The third argument.
d? Object The fourth argument.

The form of name decides what is called:

NameCalls
nameA global function.
FUNC.nameA function found at a path.
plugin/methodA method of a plugin.
*/methodA method of the common plugin.
-component/methodA component method, through SETTER().
#eventAn event, through EMIT().

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.

Call a function by path
FUNC.sum = function(a, b) {
	console.log(a + b); // 5
};

EXEC('FUNC.sum', 2, 3);
Wait for a function
EXEC('app.start @important', 'now');

setTimeout(function() {
	window.app = {};
	app.start = function(value) {
		console.log(value); // now
	};
}, 100);
method

EXTENSION(name, [config], callback)

Extends a component or a plugin.
ParameterTypeDescription
name String The component name, or @ followed by the plugin name.
config? String|Object Configuration added to each instance.
callback Function 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.

Add a method to a component
<ui-component name="box"></ui-component>

<script>
COMPONENT('box', function(self) {});

EXTENSION('box', 'color:red', function(self, config) {
	self.describe = function() {
		return config.color;
	};
});

ON('ready', function() {
	console.log(FIND('box').describe()); // red
});
</script>
method

FIND(selector, [all])

Finds a component that is ready.
ParameterTypeDescription
selector String The name, the identifier or the path.
all? Boolean Returns all the matches in an array. Default: false

Returns Component|Array The first component, or an array when all is true.

The selector is a component name, #id for an identifier, or .path for a path.

Find by name and by path
<ui-component name="field" path="form.name"></ui-component>

<script>
COMPONENT('field', function(self) {});

ON('ready', function() {
	console.log(FIND('field').name); // field
	console.log(FIND('.form.name').path.path); // form.name
	console.log(FIND('field', true).length); // 1
});
</script>
method

FLAGS(flags, [callback])

Emits flags and then runs a function.
ParameterTypeDescription
flags String The flags, for example @loading @save.
callback? Function A function that runs afterwards.

Each flag emits the event @flag name, which you can capture with ON(). See Flags and path modifiers.

Capture a flag
ON('@flag loading', function() {
	console.log('flag captured'); // flag captured
});

FLAGS('@loading', function() {
	console.log('done'); // done
});
method

FN(code)

Compiles an arrow function from a string.
ParameterTypeDescription
code String 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.

Compile functions
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
method

FREE()

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.

Remove a detached component
<ui-component name="box" path="form.name"></ui-component>

<script>
COMPONENT('box', function(self) {});

ON('ready', function() {
	$('ui-component').remove();
	FREE();
	console.log(COMPONENTS('form').length); // 0
});
</script>
property

FUNC

An empty object for the functions of your app.

Returns Object The container.

Functions stored here can be called by path with EXEC().

Store a function
FUNC.hello = function() {
	return 'Hello';
};

console.log(FUNC.hello()); // Hello
method

GET(path, [noflags])

Reads the value of a path.
ParameterTypeDescription
path String The path, optionally with flags.
noflags? Boolean Reads the value without applying the flags. Default: false

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.

Read values
SET('user.name', 'Peter');

console.log(GET('user.name')); // Peter
console.log(GET('user')); // {"name":"Peter"}
method

GUID([length])

Generates a random identifier.
ParameterTypeDescription
length? Number 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.

Generate identifiers
console.log(GUID().length); // 36
console.log(GUID(10).length); // 10
method

HASH(value)

Creates a numeric hash of a value.
ParameterTypeDescription
value String|Number|Boolean|Object|Date 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.

Hash a string
console.log(HASH('hello')); // 99162322
method

HIDDEN(element)

Checks whether an element nested in the page is hidden.
ParameterTypeDescription
element jQuery|Element 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().

Check an element
<main><div id="a" style="display:none"></div><div id="b"></div></main>

<script>
console.log(HIDDEN($('#a'))); // true
console.log(HIDDEN($('#b'))); // false
</script>
method

IMPORT(url, [target], [callback], [prepare])

Loads a script, a stylesheet or a piece of HTML.
ParameterTypeDescription
url String The address and optional keywords.
target? String|jQuery|Element The element that receives HTML content. Default: body
callback? Function A function that runs when the content is loaded.
prepare? Function 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:

KeywordMeaning
<name>Skips the import when the global variable name exists.
.js, .css, .htmlSets the type of the content when the address does not show it.
@singletonImports the address only once.
@prependInserts 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.

Insert a piece of HTML
<div id="menu"></div>

<script>
IMPORT('/parts/menu.html', '#menu', function() {
	console.log($('#menu').html()); // <b>Menu</b>
});
</script>
Skip a library that exists
IMPORT('<jQuery> /js/jquery.min.js', function() {
	console.log('jQuery is available'); // jQuery is available
});
method

INC(path, [value])

Increases the number stored in a path.
ParameterTypeDescription
path String The path.
value? Number The amount to add. Default: 1

An empty path starts at 0. A string is converted to a number. Use a negative value to decrease the number.

Increase a counter
SET('stats.visits', 10);
INC('stats.visits');
INC('stats.visits', 5);
console.log(GET('stats.visits')); // 16
method

inDOM(element)

Checks whether an element is attached to the document body.
ParameterTypeDescription
element Element A DOM element.

Returns Boolean true when the element is attached, otherwise nothing.

Check an element
console.log(inDOM(document.body)); // true
console.log(!!inDOM(document.createElement('div'))); // false
property

isIE

Tells whether the browser is Internet Explorer.

Returns Boolean The result of the detection.

property

isMOBILE

Tells whether the user agent belongs to a mobile device.

Returns Boolean The result of the detection.

property

isPRIVATEMODE

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.

property

isROBOT

Tells whether the user agent belongs to a search engine or a crawler.

Returns Boolean The result of the detection.

property

isSTANDALONE

Tells whether the page runs as an installed web app.

Returns Boolean The result of the detection.

property

isTOUCH

Tells whether the device supports touch input.

Returns Boolean The result of the detection.

property

jComponent

The main object of the library.

Returns Object The main object.

The same object as MAIN.

method

LOCALIZE(text)

Loads translations into the dictionary.
ParameterTypeDescription
text String 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 and used by TRANSLATE(). See Localization.

Load a translation
var key = 'T' + HASH('Hello').toString(36);

LOCALIZE(key + ' : Hola');
console.log(TRANSLATE('@(Hello)')); // Hola
property

M

A short name of the main object.

Returns Object The main object.

The same object as MAIN.

property

MAIN

The main object of the library.

Returns Object The main object.

Described on its own page: MAIN.

property

MONTHS

The English names of the months, starting with January.

Returns Array Twelve strings.

Read a month
console.log(MONTHS[0]); // January
method

NEWUIBIND(element, [path], [config])

Creates a data binding on an element from code.
ParameterTypeDescription
element jQuery|Element The element.
path? String The path to observe.
config? String The binding commands.

The binding works like the ui-bind element. Without path and config, the values are read from the attributes of the element.

Bind an element to a path
<div id="name"></div>

<script>
SET('user.name', 'Peter');
NEWUIBIND($('#name'), 'user.name', 'text:value');

setTimeout(function() {
	console.log($('#name').html()); // Peter
}, 200);
</script>
method

NODEINDEXOF(element)

Returns the position of an element among its siblings.
ParameterTypeDescription
element jQuery|Element The element.

Returns Number The zero-based position.

Read a position
<ul><li id="a">A</li><li id="b">B</li></ul>

<script>
console.log(NODEINDEXOF($('#b'))); // 1
</script>
method

NODEINSERT(element, reference, [before])

Inserts an element next to another element.
ParameterTypeDescription
element jQuery|Element The element to insert.
reference jQuery|Element The reference element.
before? Boolean Inserts the element in front of the reference. Default: false
Move an element
<ul><li id="a">A</li><li id="b">B</li><li id="c">C</li></ul>

<script>
NODEINSERT($('#c'), $('#a'), true);
console.log($('ul').text()); // CAB
</script>
method

NODEMOVE(element, [up])

Moves an element one position among its siblings.
ParameterTypeDescription
element jQuery|Element The element.
up? Boolean Moves the element towards the start. Otherwise it moves towards the end. Default: false
Reorder a list
<ul><li id="a">A</li><li id="b">B</li><li id="c">C</li></ul>

<script>
NODEMOVE($('#b'), true);
console.log($('ul').text()); // BAC
</script>
method

NOOP()

A function that does nothing.

Use it as a default callback.

A default callback
var callback = NOOP;
console.log(typeof(callback)); // function
method

NOTFOCUSED()

Checks whether the page is in the background.

Returns Boolean true when the document is hidden.

Check the page
console.log(NOTFOCUSED()); // false
property

NOW

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.

Read the date
console.log(NOW instanceof Date); // true
method

NUL(path)

Sets a path to null.
ParameterTypeDescription
path String The path.

NULL() is the same function under another name.

Clear a value
SET('user.name', 'Peter');
NUL('user.name');
console.log(GET('user.name')); // null
method

OFF(name, [callback])

Removes event handlers.
ParameterTypeDescription
name String The name of the event.
callback? Function The handler to remove.

Without callback, all the handlers of the event are removed. Several events can be joined with +.

Remove a handler
var count = 0;
var handler = function() {
	count++;
};

ON('refresh', handler);
EMIT('refresh');
OFF('refresh', handler);
EMIT('refresh');
console.log(count); // 1
method

ON(name, callback, [init])

Registers an event handler.
ParameterTypeDescription
name String The name of the event.
callback Function The handler. It receives the arguments of the event.
init? Boolean Also calls the handler once, without arguments. Default: false

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.

Capture two events
var count = 0;

ON('saved + removed', function() {
	count++;
});

EMIT('saved');
EMIT('removed');
console.log(count); // 2
method

PARSE(value)

Parses JSON and converts date strings to Date objects.
ParameterTypeDescription
value String|Object 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.

Parse JSON
var data = PARSE('{"created":"2024-05-01T10:00:00.000Z"}');
console.log(data.created instanceof Date); // true
console.log(PARSE('invalid')); // null
method

PIPE(name, [data], callback, [scope])

Calls an operation on the address from DEF.pipe.
ParameterTypeDescription
name String The name of the operation, optionally followed by keywords.
data? Object The data of the operation.
callback Function|String A function or a path that receives the response.
scope? Object The object in which a callback path is resolved. Default: window

It works like API(), with the address taken from DEF.pipe.

Call an operation
DEF.pipe = '/pipe/';

PIPE('orders_list', function(response) {
	console.log(response.length); // 1
});
method

PLUGIN(name, [config], callback, [dependencies])

Registers a plugin declaration.
ParameterTypeDescription
name String The name of the plugin.
config? String The default configuration in the form key:value;key:value.
callback Function The declaration: function(self, config).
dependencies? String|Array Addresses to import first.

The callback runs when a ui-plugin element with this path is created. The name * registers the common plugin. See Plugins and the Plugin object.

Declare a plugin
<ui-plugin path="users"></ui-plugin>

<script>
PLUGIN('users', function(self) {
	self.hello = function(name) {
		console.log('Hello ' + name); // Hello Peter
	};
});

ON('ready', function() {
	EXEC('users/hello', 'Peter');
});
</script>
property

PLUGINS

The running plugin instances, by name.

Returns Object The plugin instances.

Read a plugin
<ui-plugin path="users"></ui-plugin>

<script>
PLUGIN('users', function(self) {});

ON('ready', function() {
	console.log(Object.keys(PLUGINS)); // ["users"]
});
</script>
property

PREF

Persistent user preferences.

Returns Object The preferences.

Described on its own page: PREF.

method

PUSH(path, value)

Adds an item to the array stored in a path and notifies the path.
ParameterTypeDescription
path String The path of an existing array.
value Object The item.

Write ^ in front of the path to add the item at the beginning of the array.

Add items
SET('tags', ['b']);
PUSH('tags', 'c');
PUSH('^tags', 'a');
console.log(GET('tags')); // ["a","b","c"]
method

QUERIFY([url], data)

Adds data to an address as a query string.
ParameterTypeDescription
url? String The address.
data Object 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.

Build addresses
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
property

REPO

An empty object for the shared data of your app.

Returns Object The container.

Store a value
REPO.title = 'My app';
console.log(REPO.title); // My app
method

RESET(path)

Resets the state of the components bound to a path.
ParameterTypeDescription
path String The path.

The touched and modified states return to their defaults. The value of the path does not change.

Reset a form
<ui-component name="field" path="form.name"></ui-component>

<script>
COMPONENT('field', function(self) {});

ON('ready', function() {
	SET('form.name @change', 'Peter');
	console.log(FIND('field').config.modified); // 1
	RESET('form');
	console.log(FIND('field').config.modified); // 0
	console.log(GET('form.name')); // Peter
});
</script>
method

SCROLLBAR(element, [options])

Adds a custom scrollbar to an element.
ParameterTypeDescription
element jQuery The element.
options? Object The options.

Returns Object The scrollbar.

Options:

OptionTypeDescription
nativeBooleanKeeps the scrollbar of the browser and only sets the overflow.
orientationStringx or y. By default, both directions are active.
visibleX, visibleYBooleanKeeps the track visible when there is nothing to scroll.
wrapBooleanfalse uses the existing content as the scroll area.
controlsjQueryThe element that receives the scrollbar tracks.
shadowBooleanAdds shadows on the scrollable edges.
paddingNumberThe distance of the tracks from the edge. Default 5.
minsizeNumberThe minimum size of the bar. Default 50.
thicknessNumberThe thickness used when CSS does not define it. Default 10.
margin, marginX, marginYNumberAdjust the size of the scroll area.
offsetX, offsetYNumberAdjust the measured size of the element.
floatingBooleanfalse reserves space for the bars.
parentString|jQueryThe element whose size is used.
intervalNumberThe time between size checks, in milliseconds. Default 54321.
autoresizeBooleanfalse stops measuring the element again when the window is resized. Default true.
onscroll, onidle, onresizeFunctionHandlers that receive the scrollbar.

The returned object provides:

MemberDescription
areaThe scrolling element.
bodyThe element with the content.
elementThe 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 report scrolling.

Scroll from code
<div id="panel" style="width:200px;height:100px"><div style="height:600px">Content</div></div>

<script>
var scrollbar = SCROLLBAR($('#panel'));

scrollbar.area.css('overflow', 'auto');
scrollbar.resize(false, true);
scrollbar.scrollTop(30);
console.log(scrollbar.scrollTop()); // 30
scrollbar.scrollTop('+20');
console.log(scrollbar.scrollTop()); // 50
</script>
method

SCROLLBARWIDTH()

Returns the width of the scrollbar of the browser.

Returns Number The width in pixels.

Read the width
console.log(typeof(SCROLLBARWIDTH())); // number
method

SEEX(name, [a], [b], [c], [d])

Calls a function or writes a value, depending on the name.
ParameterTypeDescription
name String The target.
a? Object The first argument.
b? Object The second argument.
c? Object The third argument.
d? Object 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().

Write to a path
SEEX('form.name', 'Peter');
console.log(GET('form.name')); // Peter
Call a global function
window.notify = function(text) {
	console.log(text); // Saved
};

SEEX('notify', 'Saved');
method

SET(path, value)

Writes a value to a path and notifies everything that observes it.
ParameterTypeDescription
path String The path, optionally with flags.
value Object 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 and Flags and path modifiers.

Write values
SET('user.name', 'Peter');
SET('user.tags[]', 'admin');
console.log(GET('user')); // {"name":"Peter","tags":["admin"]}
Write a value from the current one
SET('cart.count', 1);
SET('cart.count', value => value + 1);
console.log(GET('cart.count')); // 2
method

SETTER(name, [a], [b], [c], [d])

Calls a method on the components that match a selector.
ParameterTypeDescription
name String The selector and the method.
a? Object The first argument.
b? Object The second argument.
c? Object The third argument.
d? Object The fourth argument.

The name has the form selector/method:

SelectorMatches
nameComponents with this name.
#idThe 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 !.

Call a component method
<ui-component name="counter"></ui-component>

<script>
COMPONENT('counter', function(self) {
	self.add = function(value) {
		console.log(value); // 5
	};
});

ON('ready', function() {
	SETTER('counter/add', 5);
});
</script>
method

setTimeout2(name, callback, timeout, [limit], [param])

Runs a function after a delay, restarting the delay on each call with the same name.
ParameterTypeDescription
name String The name of the timer.
callback Function The function.
timeout Number The delay in milliseconds.
limit? Number The maximum number of calls in one waiting period.
param? Object 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.

Run once after the last call
var count = 0;
var run = function() {
	count++;
	console.log(count); // 1
};

setTimeout2('search', run, 50);
setTimeout2('search', run, 50);
setTimeout2('search', run, 50);
method

STRINGIFY(value, [compress], [fields], [encrypt])

Serializes a value to JSON.
ParameterTypeDescription
value Object The value.
compress? Boolean Removes empty values. Default: false
fields? Array|Object|Function The keys to keep.
encrypt? Boolean|String true encodes the JSON with ENCRYPT(). 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.

Compress and filter
var data = { name: ' Peter ', note: '', age: 30 };

console.log(STRINGIFY(data, true)); // {"name":"Peter","age":30}
console.log(STRINGIFY(data, false, ['age'])); // {"age":30}
Encode the JSON
var text = STRINGIFY({ id: 5 }, false, null, 'secret');
console.log(DECRYPT(text, 'secret')); // {"id":5}
method

STYLE(value, [id], [selector])

Adds CSS to the page.
ParameterTypeDescription
value String|Array The CSS.
id? String The identifier of the style element.
selector? String 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.

Add scoped styles
STYLE('b { color: red }', 'theme', '.panel');
console.log($('#csstheme').html()); // .panel b{ color: red }
method

TAPI(name, [data], callback, [scope])

Calls a Total.js API operation on the address from DEF.api.
ParameterTypeDescription
name String The name of the operation, optionally followed by keywords.
data? Object The data of the operation.
callback Function|String A function or a path that receives the response.
scope? Object The object in which a callback path is resolved. Default: window

It works like API(), with the address taken from DEF.api.

Store a response in a path
DEF.api = '/admin/api/';

TAPI('users_list', { page: 1 }, 'users.items');

WATCH('users.items', function(value) {
	console.log(value.length); // 2
});
property

TEMP

An object for short-lived data.

Returns Object The container.

The library replaces it with an empty object every minute.

Store a value
TEMP.result = 5;
console.log(TEMP.result); // 5
method

TOGGLE(path)

Inverts the boolean value of a path.
ParameterTypeDescription
path String The path.
Toggle a value
SET('menu.open', false);
TOGGLE('menu.open');
console.log(GET('menu.open')); // true
property

Total

The main object of the library.

Returns Object The main object.

The same object as MAIN.

method

TRANSLATE(text)

Replaces the @(text) markup with translations.
ParameterTypeDescription
text String The text with the markup.

Returns String The translated text.

Text without a translation stays in its original language. Translations are loaded with LOCALIZE().

Translate a text
LOCALIZE('T' + HASH('Yes').toString(36) + ' : Ano');
console.log(TRANSLATE('@(Yes) / @(No)')); // Ano / No
method

UNAUTHORIZED(...permissions)

Checks the permissions of the signed-in user.
ParameterTypeDescription
permissions String 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.

Check a permission
window.user = { roles: ['editor'] };

console.log(UNAUTHORIZED('editor')); // false
console.log(UNAUTHORIZED('admin')); // true
method

UNWATCH(path, [callback])

Removes watchers from a path.
ParameterTypeDescription
path String The path. Several paths can be joined with +.
callback? Function The watcher to remove.

Without callback, all the watchers of the path are removed.

Stop watching
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
method

UPD(path)

Notifies a path after its value was changed directly.
ParameterTypeDescription
path String The path, optionally with flags.

UPDATE() is the same function under another name.

Notify after a direct change
window.form = { name: 'A' };

WATCH('form.name', function(value) {
	console.log(value); // B
});

form.name = 'B';
UPD('form.name');
method

VISIBLE(element, [threshold], [mode])

Checks the vertical position of an element relative to the viewport.
ParameterTypeDescription
element jQuery|Element The element.
threshold? Number The number of pixels of the element that must be inside the viewport. Default: 0
mode? String visible, above or below. Default: visible

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.

Check an element
<div id="top">Top</div>
<div style="height:5000px"></div>
<div id="far">Far</div>

<script>
console.log(VISIBLE($('#top'))); // true
console.log(VISIBLE($('#far'))); // false
console.log(VISIBLE($('#far'), 0, 'below')); // true
</script>
property

W

A short name of the window object.

Returns Object The window object.

Compare the objects
console.log(W === window); // true
method

WAIT(condition, callback)

Runs a function when a condition is met.
ParameterTypeDescription
condition Function|String A function or a path.
callback Function 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.

Wait for a value
WAIT('app.config', function() {
	console.log(GET('app.config.name')); // Demo
});

setTimeout(function() {
	SET('app.config', { name: 'Demo' });
}, 100);
method

WARN(...values)

Prints a warning to the browser console.
ParameterTypeDescription
values Object The values to print.
method

WATCH(path, callback, [init])

Observes changes of a path.
ParameterTypeDescription
path String The path.
callback Function A function that receives (value, flags, path): the watched value, the flags and the changed path.
init? Boolean Also calls the watcher once after the registration. Default: false

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 +.

Observe a path
WATCH('user.name', function(value, flags, path) {
	console.log(value, path); // Peter user.name
});

SET('user.name', 'Peter');
property

WH

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.

Read the height
ON('ready', function() {
	console.log(typeof(WH)); // number
});
method

WIDTH([element])

Returns the name of the device size for the width of an element.
ParameterTypeDescription
element? jQuery The measured element. Default: window

Returns String The name of the size.

The sizes xs, sm, md and lg are defined in DEF.devices.

Measure an element
<div id="box" style="width:800px"></div>

<script>
console.log(WIDTH($('#box'))); // sm
</script>
property

WW

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.

Read the width
ON('ready', function() {
	console.log(typeof(WW)); // number
});
Made in Europe