Spanish Total.js
English
Documentation For AI agents
Contents

Global functions

The functions and objects that jComponent adds to the window object.

.md GitHub
On this page

jComponent adds these functions and objects to window, so they can be used anywhere without an import. To learn how paths work first, read Paths.

API

method

ACMD(name, [...args])

Creates a function that calls CMD() later.
ParameterTypeDescription
name String The name of the command.
...args? Object The first arguments.

Returns Function The function to call.

The argument of the created function is added as the last argument of the command.

Use it as a callback
ON('cmd', function(name, value) {
	console.log(name, value); // refresh 1
});
ACMD('refresh')(1);
method

ADAPT(path, id, text)

Prepares imported text for a path and an identifier.
ParameterTypeDescription
path String The value for ~PATH~ and CLASS.
id String The value for ~ID~.
text String The text.

Returns String The changed text.

The text is translated, --name-- variables are replaced, ~CDN~ becomes DEF.cdn, ~PATH~ and CLASS become the path, and ~ID~ becomes the identifier.

Replace the markers
console.log(ADAPT('users', 'form1', '~PATH~ and ~ID~')); // users and form1
method

ADD(value, [element], [config], [content])

Adds a component to the page.
ParameterTypeDescription
value String|Object|Array The component.
element? Element|jQuery|Component The parent element. Default: document.body
config? Object|String The configuration.
content? String The inner HTML.

A string has the form name__path__config. A leading ! skips the component when it is already declared. An object can have the fields name, path, config, element and prepend. An array adds several components.

Add a component
ADD('box__data.title__size:10');
setTimeout(function() {
	console.log(FIND('box').config.size); // 10
}, 1200);
method

AEXEC(path, [...args])

Creates a function that calls EXEC() later.
ParameterTypeDescription
path String The target.
...args? Object The first arguments.

Returns Function The function to call.

The argument of the created function is added as the last argument.

Use it as a callback
window.save = value => console.log(value); // 5
AEXEC('save')(5);
method

AJAX(url, [data], [callback], [delay])

Sends an HTTP request.
ParameterTypeDescription
url String The method and the URL.
data? Object|String The data. A GET request sends it in the query string.
callback? Function|String function(response, err, output), or a path.
delay? Number Waits this many milliseconds before sending.

Returns Promise Only when no callback is given.

The URL has the form METHOD /path/. More items can follow it, separated by a space:

ItemMeaning
!METHODSends cookies with the request
{ "Name": "value" }Request headers
<5 minutes>Caches the response, as in AJAXCACHE()
(name)Applies the settings from AJAXCONFIG()
repeatRepeats the request when the server is not available
cancelCancels the previous unfinished request to the same URL
urlencodedSends the data as a URL-encoded form
jsonAccepts only a JSON response
errorPasses the response through ERROR()
noencrypt, nodecrypt, nocsrfSkips encryption, decryption or the CSRF header
#idNames the request for cancel, or waits for a code list
@flagEmits a custom flag

The callback receives the response, the status code on an error, and an object with the details of the request. A string callback is a path where the response is stored. Without a callback, the function returns a Promise, which is rejected on a status above 399.

Send data
AJAX('POST /api/users/', { name: 'Peter' }, function(response, err) {
	console.log(response.method, response.url); // POST /api/users/
	console.log(response.body); // {"name":"Peter"}
});
Use a Promise
(async function() {
	var response = await AJAX('GET /api/users/');
	console.log(response.url); // /api/users/
})();
Handle an error
AJAX('GET /api/missing/', function(response, err) {
	console.log(err, response); // 404 Not found
});
method

AJAXCACHE(url, [data], callback, expire, [delay], [clear])

Sends a request and caches the response.
ParameterTypeDescription
url String The method and the URL.
data? Object The data.
callback Function|String function(response, cached), or a path.
expire String For example 5 minutes or session.
delay? Number Waits this many milliseconds before reading.
clear? Boolean With true, ignores the stored response.

The callback receives the response and true when it comes from the cache. The value session for expire keeps the response in memory until the page is reloaded.

Cache a response
AJAXCACHE('GET /api/users/', function(response, cached) {
	console.log('first', cached); // first false
	AJAXCACHE('GET /api/users/', function(response, cached) {
		console.log('second', cached); // second true
	}, '5 minutes');
}, '5 minutes');
method

AJAXCACHEREVIEW(url, [data], callback, expire, [delay], [clear])

Returns the cached response and then checks the server for a newer one.
ParameterTypeDescription
url String The method and the URL.
data? Object The data.
callback Function|String function(response, cached, updated), or a path.
expire String For example 5 minutes.
delay? Number Waits this many milliseconds before reading.
clear? Boolean With true, ignores the stored response.

When the server returns different data, the callback runs again with false and true as its second and third arguments.

Refresh a cached response
AJAXCACHE('GET /api/time/', function() {
	AJAXCACHEREVIEW('GET /api/time/', function(response, cached, updated) {
		console.log(response.value, cached, updated === true); // 2 false true
	}, '5 minutes');
}, '5 minutes');
method

AJAXCONFIG(name, fn)

Declares settings that a request can apply by name.
ParameterTypeDescription
name String The name of the settings.
fn Function function(options).

A request applies them with (name) in its URL. The function receives the options of the request.

Add a header
AJAXCONFIG('secure', function(options) {
	options.headers['X-Token'] = 'abc';
});
ON('request', function(opt) {
	console.log(opt.headers['X-Token']); // abc
	opt.respond({});
});
AJAX('GET /api/users/ (secure)', NOOP);
method

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

Calls a Total.js API endpoint.
ParameterTypeDescription
url String The endpoint and the schema.
data? Object The data.
callback? Function|String function(response, err, output), or a path.

Returns Object|Promise The object described above, or a Promise.

The URL has the form /api/ schema. The request is a POST with the name of the schema and the data in its body. Without a callback, the function returns a Promise. With a callback, it returns an object with params(value), which fills the parameters of the schema, and data(value), which replaces the data.

Call an endpoint
API('/api/ users_save', { name: 'Peter' }, function(response) {
	console.log(response.url); // /api/
	console.log(response.body); // {"schema":"users_save","data":{"name":"Peter"}}
});
method

APPEARANCE(options)

Sets the look of the application.
ParameterTypeDescription
options Object The CSS variables and the fields dark and large.

Every field becomes a CSS variable on :root. dark and large switch the classes ui-dark and ui-large on the body. color is a six-digit hexadecimal color, which also sets DEF.color and the variable --rgb.

Use a dark theme
APPEARANCE({ dark: true, color: '#336699' });
console.log($('#cssappearance').html()); // :root{--color:#336699;--rgb:51,102,153}
console.log($('body').hclass('ui-dark')); // true
method

ASETTER(selector, method, [...args])

Creates a function that calls SETTER() later.
ParameterTypeDescription
selector String A selector as in FIND().
method String The name of the method.
...args? Object The first arguments of the method.

Returns Function The function to call.

The argument of the created function is added as the last argument of the method, so it fits a request callback.

Use it as a callback
ON('ready', function() {
	var fn = ASETTER('box', 'hello');
	fn('Peter');
	console.log(typeof(fn)); // function
});
method

ATTRD(element, [name])

Reads a data- attribute from an element or its parents.
ParameterTypeDescription
element Element|jQuery|Event|Object The source.
name? String The name of the attribute. Default: id

Returns String The value.

A plain object returns its field of that name.

Read an identifier
<div id="row" data-id="15" data-type="user"></div>
<script>
console.log(ATTRD($('#row'))); // 15
console.log(ATTRD($('#row'), 'type')); // user
</script>
method

BIND(path)

Refreshes the data bindings of a path without notifying components or watchers.
ParameterTypeDescription
path String|Array One path or a list of paths.
Refresh a binding
<span id="name" data-bind="user.name__text"></span>
<script>
SET('user', { name: 'Peter' });
setTimeout(function() {
	GET('user').name = 'Anna';
	BIND('user.name');
	setTimeout(function() {
		console.log($('#name').text()); // Anna
	}, 300);
}, 300);
</script>
method

BLOCKED(name, timeout, [callback])

Limits how often an action can run.
ParameterTypeDescription
name String The name of the action.
timeout Number|String Milliseconds, or a value such as 5 seconds.
callback? Function Runs when the action is not blocked.

Returns Boolean true when the action is blocked.

The first call returns false and blocks the name for the given time. A block longer than 10 seconds is kept in the browser storage.

Allow one call per second
console.log(BLOCKED('save', 1000)); // false
console.log(BLOCKED('save', 1000)); // true
method

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

Reads or writes a value in the browser cache.
ParameterTypeDescription
key String The key.
value? Object The value to store.
expire? String|Number For example 1 day, session, or milliseconds.

Returns Object The stored value.

A value is stored only with an expiration. The value session keeps it in memory until the page is reloaded.

Store a value
CACHE('profile', { name: 'Peter' }, '1 day');
console.log(CACHE('profile')); // {"name":"Peter"}
method

CACHEPATH(path, expire, [rebind])

Keeps the value of a path in the browser cache.
ParameterTypeDescription
path String The path.
expire String For example 1 month.
rebind? Boolean With false, the stored value is not restored. Default: true

Every change of the path is stored, and the stored value is restored on the next visit. With the form path__value, the expression is the value used when nothing is stored.

Remember a value
CACHEPATH('settings.theme', '1 month');
SET('settings.theme', 'dark');
console.log(CACHE('PATHS')); // {"settings.theme":"dark"}
method

CAN(path, [flags])

Tells whether a form can be submitted.
ParameterTypeDescription
path String The path, optionally with .* for everything below it.
flags? String|Array visible or hidden limits the check to those components.

Returns Boolean The result.

The result is true when at least one component on the path is touched and none is invalid. A path with no components also returns true.

Enable a submit button
ON('ready', function() {
	console.log(CAN('form.*')); // false
	SET('form', { name: 'Peter', age: 30 });
	CHANGE('form.name');
	console.log(CAN('form.*')); // true
});
method

CHANGE(path, [value])

Marks the components on a path as touched and modified.
ParameterTypeDescription
path String The path of the value. See Paths.
value? Boolean With false, the marks are removed. Default: true
Mark a field as changed
ON('ready', function() {
	CHANGE('form.age');
	console.log(MODIFIED('form.*')); // ["form.age"]
});
method

CL(name, callback)

Waits until code lists are loaded.
ParameterTypeDescription
name String The name of the code list.
callback Function Runs when the lists are ready.

Several names can be separated by a comma. Loaded values are stored in DEF.cl.

Wait for a code list
CL_INIT('countries', next => next(['SK', 'CZ']));
CL('countries', function() {
	console.log(DEF.cl.countries); // ["SK","CZ"]
});
method

CL_INIT(name, source, [expire], [init])

Declares how a code list is loaded.
ParameterTypeDescription
name String The name of the code list.
source Function|String The loader.
expire? String The list is loaded again after this time.
init? Boolean With true, loads the list immediately.

The source is a function that receives next(value), or a string. A string that starts with an HTTP method goes to AJAX(), and any other string to TAPI(). CLINIT() is the same function.

Load a list from a URL
CL_INIT('roles', 'GET /api/roles/', true);
setTimeout(function() {
	console.log(DEF.cl.roles.url); // /api/roles/
}, 300);
method

clearTimeout2(name)

Cancels a named timer.
ParameterTypeDescription
name String The name of the timer.

Returns Boolean true when a timer was running.

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

CLINIT(name, source, [expire], [init])

The same function as CL_INIT().
Same function
console.log(CLINIT === CL_INIT); // true
method

CLONE(value, [nopath])

Creates a deep copy of a value.
ParameterTypeDescription
value Object|String The value or a path.
nopath? Boolean With true, a string is returned as it is.

Returns Object The copy.

A string is treated as a path, and the value of the path is cloned.

Clone a value
SET('user', { name: 'Peter' });
var copy = CLONE('user');
copy.name = 'Anna';
console.log(GET('user.name')); // Peter
console.log(copy.name); // Anna
method

CLRELOAD(name, [callback])

Loads code lists again.
ParameterTypeDescription
name String The name of the code list.
callback? Function Runs when the lists are loaded.

Several names can be separated by a comma.

Reload a list
var count = 0;
CL_INIT('numbers', next => next([++count]), true);
setTimeout(function() {
	CLRELOAD('numbers', function() {
		console.log(DEF.cl.numbers); // [2]
	});
}, 100);
method

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

Runs a command in all components that registered it.
ParameterTypeDescription
name String The name of the command.
a? Object Up to five arguments, a to e.

Components register commands with self.command().

Run a command
ON('ready', function() {
	CMD('box.ping', 5);
});
ON('cmd', function(name, value) {
	console.log(name, value); // box.ping 5
});
method

COMPILE([container])

Searches the page for new components and bindings.
ParameterTypeDescription
container? Element|jQuery Limits the search to this element.

Call it after adding HTML by hand.

Compile new HTML
$(document.body).append('<ui-component name="box" path="data.new"></ui-component>');
COMPILE();
setTimeout(function() {
	console.log(FIND('box').path); // data.new
}, 500);
method

COMPONENT(name, [config], declaration, [dependencies])

Declares a component.
ParameterTypeDescription
name String The name of the component.
config? String|Object The default configuration.
declaration Function function(self, config, cls).
dependencies? Array Files to import first, or component names that start with @.

Several names can be separated by a comma. A version can follow the name: box@2. The whole topic is explained in Creating components, and the object the declaration receives is described in Component.

Declare a component
<ui-component name="hello"></ui-component>
<script>
COMPONENT('hello', 'name:World', function(self, config) {
	self.make = () => self.element.text('Hello ' + config.name);
});
ON('ready', function() {
	console.log($('ui-component').text()); // Hello World
});
</script>
method

COMPONENTS(path)

Lists the components on a path.
ParameterTypeDescription
path String The path with optional flags.

Returns Array The components.

The path is written without .*. Flags after the path filter the list: @visible, @hidden, @touched, @modified, @required, @invalid, @valid, @disabled and @enabled.

Filter the components
ON('ready', function() {
	console.log(COMPONENTS('form').length); // 2
	SET('form.name', 'Peter');
	console.log(COMPONENTS('form @invalid').map(com => com.path)); // ["form.age"]
});
method

CONFIG(selector, config)

Sets the configuration of components before they start.
ParameterTypeDescription
selector String|Function Which components to configure.
config Object|String|Function The configuration, or a function that returns it.

The selector is a component name, .path, #id, or a function that receives the component and returns a boolean. Parts separated by a space must all match, and a comma separates alternatives. Call it before the components are compiled.

Configure by name
CONFIG('box', { size: 10 });
ON('ready', function() {
	console.log(FIND('box').config.size); // 10
});
property

COOKIES

An object for reading and writing cookies.

It has the methods get(name), set(name, value, expire, [samesite]) and rem(name). expire is a Date or a value such as 1 day.

Read the value
COOKIES.set('theme', 'dark', '1 day');
console.log(COOKIES.get('theme') === 'dark' || location.protocol === 'file:'); // true
method

COPY(source, target)

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

Returns Object The target object.

Objects inside the source are cloned.

Copy fields
var target = COPY({ a: 1 }, { b: 2 });
console.log(target); // {"b":2,"a":1}
method

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

The same function as STYLE().
Same function
console.log(CSS === STYLE); // true
method

DAPI(name, [data], [callback])

Calls the API endpoint set in DEF.api.
ParameterTypeDescription
name String The name of the schema.
data? Object The data.
callback? Function|String function(response, err, output), or a path.

Returns Object|Promise The same as API().

DEF.api is a URL, or a function that receives the name and the data and returns the value for API().

Use the default endpoint
DEF.api = '/api/';
DAPI('users_list', null, function(response) {
	console.log(response.url, response.body.schema); // /api/ users_list
});
property

DAYS

The names of the days, starting with Sunday.
Read the value
console.log(DAYS[0]); // Sunday
method

DEBUG()

Turns on the debug mode.

Calls of missing methods write a warning to the console, and API() adds the schema to the URL. The mode cannot be turned on after DEF.secret() has set a key.

Warn about a missing method
DEBUG();
EXEC('missing.method');
console.log('done'); // done
method

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

Decodes a value from ENCRYPT().
ParameterTypeDescription
value String The encoded value.
key? String The key.
type? String The prefix of the value.

Returns Object The value, or undefined when the key or the prefix does not match.

JSON is parsed back to an object.

Use a wrong key
var token = ENCRYPT('Peter', 'secret');
console.log(DECRYPT(token, 'secret')); // Peter
console.log(DECRYPT(token, 'other') === undefined); // true
property

DEF

The configuration of the library. See DEF.
Read the value
console.log(DEF.delay); // 555
method

DEFAULT(path, [delay], [reset])

Restores the default values of the components on a path.
ParameterTypeDescription
path String The path, optionally with .* for everything below it, or path__value.
delay? Number A delay in milliseconds.
reset? Boolean With false, the state of the components is kept. Default: true

A component takes its default value from its default attribute. With the form path__value, the expression after the two underscores is written to the path as the default value instead.

Write a default object
DEFAULT('form.* __{ name: "Peter" }');
setTimeout(function() {
	console.log(GET('form')); // {"name":"Peter"}
}, 100);
method

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

Updates the children of an element so they match new HTML.
ParameterTypeDescription
element jQuery The parent.
selector String A selector of the children.
html String The new HTML.
attribute? String The attribute to compare.

Returns Object The counts add, upd and rem.

Only the changed children are added or removed. Children are compared by their HTML, or by the value of the attribute.

Update a list
<ul id="list"><li>A</li><li>B</li></ul>
<script>
var result = DIFFDOM($('#list'), 'li', '<li>B</li><li>C</li>');
console.log(result); // {"add":1,"upd":1,"rem":1}
console.log($('#list').text()); // BC
</script>
method

DISABLED(path, [flags])

The opposite of CAN().
ParameterTypeDescription
path String The path, optionally with .* for everything below it.
flags? String|Array visible or hidden limits the check to those components.

Returns Boolean The result.

Disable a submit button
ON('ready', function() {
	console.log(DISABLED('form.*')); // true
});
method

EMIT(name, [...args])

Calls the handlers of an event.
ParameterTypeDescription
name String The name of the event.
...args? Object The arguments passed to the handlers.

Returns Boolean true when the event has at least one handler.

A custom flag can follow the name, for example EMIT('ping @saved').

Emit an event
ON('hello', name => console.log(name)); // Peter
console.log(EMIT('hello', 'Peter')); // true
console.log(EMIT('unknown')); // false
property

EMPTYARRAY

A frozen empty array.
Read the value
console.log(Object.isFrozen(EMPTYARRAY)); // true
property

EMPTYOBJECT

A frozen empty object.
Read the value
console.log(Object.isFrozen(EMPTYOBJECT)); // true
method

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

Encodes a value into a hexadecimal string signed with a key.
ParameterTypeDescription
value String|Object The value.
key? String The key.
type? String A prefix of the result.

Returns String The encoded value.

The value is encoded, not strongly encrypted. Objects are converted to JSON.

Encode and decode
var token = ENCRYPT({ id: 5 }, 'secret');
console.log(DECRYPT(token, 'secret')); // {"id":5}
method

ENV(name, [value])

Reads or writes an environment variable.
ParameterTypeDescription
name String|Object The name, or an object with values.
value? Object The value.

Returns Object The value of the variable.

An object as the first argument writes several variables. Paths and URLs read the variables with [name]. The variables are stored in DEF.environment.

Use a variable
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 name, the version and the language of the application.
ParameterTypeDescription
name String The name of the application.
version? String The version.
language? String The language of imported HTML.
env? Object Environment variables for ENV().

The name separates the browser storage of the application. It sets DEF.localstorage, DEF.version and DEF.languagehtml.

Name the application
ENVIRONMENT('shop', '1.2', 'en', { api: '/api/' });
console.log(DEF.localstorage, DEF.version, ENV('api')); // shop 1.2 /api/
method

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

Tells whether a response contains an error.
ParameterTypeDescription
value Object|Function The response, or the success handler.
success? Function|String Runs when there is no error.
error? Function|String Runs when there is an error.

Returns Boolean|Function true when the value is an error, or the created callback.

An Error, an object with the field error, or an array whose first item has it counts as an error, and the event ERROR is emitted. success and error are functions or paths.

With a function as the first argument, ERROR(success, [error]) returns a callback for a request.

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

ERRORS(path, [flags], [highlight])

Lists the components that are touched and invalid.
ParameterTypeDescription
path String The path, optionally with .* for everything below it.
flags? String|Array visible or hidden limits the check to those components.
highlight? Boolean Refreshes the state of the found components.

Returns Array The components.

ERRORS(path, true) also refreshes the state of the components it finds.

Find the invalid fields
ON('ready', function() {
	CHANGE('form.name');
	console.log(ERRORS('form.*').map(com => com.path)); // ["form.name"]
});
method

EVALUATE(path, expression, [nopath])

Evaluates a JavaScript expression with the value of a path.
ParameterTypeDescription
path String|Object The path, or the value itself when nopath is true.
expression String The expression.
nopath? Boolean Treats the first argument as the value.

Returns Object The result of the expression.

The expression can use the variables value and path.

Evaluate an expression
SET('price', 10);
console.log(EVALUATE('price', 'value * 2')); // 20
console.log(EVALUATE(4, 'value + 1', true)); // 5
method

EXE([wait], path, [...args])

The same function as EXEC().
Same function
console.log(EXE === EXEC); // true
method

EXEC([wait], path, [...args])

Calls a function, a plugin method, a component method, a command or an event.
ParameterTypeDescription
wait? Boolean With true, waits for the target.
path String The target.
...args? Object The arguments.

The form of the path selects the target:

PathTarget
plugin/methodA method of a plugin
@plugin.methodA method of a plugin
path.to.fnA function on a path
#nameThe event name
-selector/methodA method of a component, as in SETTER()
&nameA command, as in CMD()

With true as the first argument, the call waits until the target exists. EXE() is the same function.

Call a plugin method
PLUGIN('users', function(exports) {
	exports.hello = function(name) {
		console.log(name); // Peter
	};
});
EXEC(true, 'users/hello', 'Peter');
Call a function on a path
window.app = { sum: (a, b) => console.log(a + b) };
EXEC('app.sum', 1, 2);
console.log(typeof(app.sum)); // function
method

EXT(path, value, [delay], [reset])

Merges the fields of an object into the object on a path.
ParameterTypeDescription
path String The path of the value. See Paths.
value Object The fields to merge.
delay? Number A number of 10 or more delays the change by that many milliseconds. A smaller number is the change type: 1 manual, 2 input, 3 default.
reset? Boolean With true, the components on the path are also marked as not touched and not modified.

Each field is written separately, so the other fields stay. EXTEND() is the same function. As with SET(), the first argument can be a request and value the target path.

Merge fields
SET('user', { name: 'Peter' });
EXT('user', { age: 30 });
console.log(GET('user')); // {"name":"Peter","age":30}
method

EXTEND(path, value, [delay], [reset])

The same function as EXT().
Same function
console.log(EXTEND === EXT); // true
method

EXTENSION(name, [config], declaration)

Extends a component or a plugin.
ParameterTypeDescription
name String The name of the component, or @plugin.
config? Object|String Additional configuration.
declaration Function function(self, config, cls).

The declaration runs for every instance of the component, including the existing ones. With a name that starts with @, it extends the plugin of that name.

Add a method to a component
EXTENSION('box', function(self) {
	self.bye = () => 'Bye';
});
ON('ready', function() {
	console.log(FIND('box').bye()); // Bye
});
method

FIND(selector, [many], [nocache], [callback])

Finds a component.
ParameterTypeDescription
selector String|Element What to find.
many? Boolean With true, returns all matches as an array.
nocache? Boolean Skips the cache of found components.
callback? Function Waits for the component and receives it.

Returns Component|Array The found component, or an array with many. Nothing is returned when a callback is used.

The selector is a component name, .path, #id, name[path] or name@version, and parts can be combined with a space. A DOM element or a jQuery object finds the components inside it.

With a callback, the search waits until the component exists. The callback can be the second or the third argument.

Find by name and path
ON('ready', function() {
	console.log(FIND('box').path); // data.box
	console.log(FIND('.data.box').name); // box
	console.log(FIND('box', true).length); // 1
});
Wait for a component
FIND('box', function(com) {
	console.log(com.name); // box
});
method

FN(expression)

Creates a function from a string.
ParameterTypeDescription
expression String The expression.

Returns Function The function.

The string is an arrow function. A string that only uses the word value becomes a function with the argument value.

Create functions
console.log(FN('(a, b) => a + b')(1, 2)); // 3
console.log(FN('value > 5')(10)); // true
method

FORMATTER(fn, [prepend])

Registers a global formatter of component values.
ParameterTypeDescription
fn Function function(path, value, type, format).
prepend? Boolean With true, the formatter runs first.

Returns Object The formatted value, when the function runs the formatters.

The function returns the new value, and undefined keeps the current one. FORMATTER(value, path, type, [format]) runs all registered formatters.

Format a value
FORMATTER(function(path, value, type) {
	if (type === 'upper')
		return value.toUpperCase();
});
console.log(FORMATTER('peter', 'user.name', 'upper')); // PETER
method

FREE([delay])

Removes unused components, bindings and watchers.
ParameterTypeDescription
delay? Number The delay in milliseconds. Default: 10

The library also does this every three minutes.

Clean up
FREE();
console.log(typeof(FREE)); // function
property

FUNC

An empty object for your own shared functions.
Read the value
FUNC.sum = (a, b) => a + b;
console.log(FUNC.sum(1, 2)); // 3
method

GET(path, [scope])

Reads the value of a path.
ParameterTypeDescription
path String The path of the value. See Paths.
scope? Object|Function|Boolean An object reads the path relative to that object. A function waits until the value is not null and then receives it. true resets the state of the components on the path.

Returns Object The value, or undefined when the path has no value. With a function as the second argument, nothing is returned.

Flags can follow the path. @clone returns a copy, @reset resets the state of the components after reading, and @modified returns only the values of the modified components.

Read a value
SET('user', { name: 'Peter', age: 30 });
console.log(GET('user.age')); // 30
console.log(GET('name', { name: 'Anna' })); // Anna
Wait for a value
GET('settings.theme', function(value) {
	console.log(value); // dark
});
setTimeout(() => SET('settings.theme', 'dark'), 100);
method

GUID([size])

Creates a random identifier.
ParameterTypeDescription
size? Number The length. Without it, the identifier has 36 characters in the form of a UUID.

Returns String The identifier.

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

HASH(value, [unsigned])

Creates a number from a value.
ParameterTypeDescription
value Object The value.
unsigned? Boolean With false, the result can be negative. Default: true

Returns Number The hash.

Objects are hashed by their JSON form. A number is returned as it is, a boolean becomes 0 or 1, and a date becomes its time.

Hash a string
console.log(HASH('abc')); // 96354
method

HIDDEN(element)

Tells whether an element is not displayed.
ParameterTypeDescription
element Element|jQuery The element.

Returns Boolean The result. A missing element returns true.

Check an element
<div id="a" style="display:none"><span></span></div>
<script>
console.log(HIDDEN($('#a')[0].firstChild)); // true
console.log(HIDDEN(null)); // true
</script>
method

IMPORT(url, [target], [callback], [insert], [preparator])

Loads a script, a style or HTML into the page.
ParameterTypeDescription
url String|Array The URL.
target? String|Element|jQuery|Component Where to put HTML. Default: body
callback? Function function(result).
insert? Boolean With false, replaces the content of the target. Default: true
preparator? Function function(response, output) changes the HTML before it is inserted.

The topic is explained in Importing content. An array of URLs is loaded one by one. A URL that starts with once or ! is loaded only once, and <path> before the URL skips the import when the path has a value. The callback receives 1 after loading and 0 when nothing was loaded.

Import HTML
<div id="target"></div>
<script>
IMPORT('/parts/hello.html', '#target', function(result) {
	console.log(result, $('#target').text()); // 1 Hello
});
</script>
method

IMPORTCACHE(url, expire, [target], [callback], [insert], [preparator])

Works like IMPORT() and caches imported HTML.
ParameterTypeDescription
url String The URL.
expire String For example 5 minutes or session.
target? String|Element|jQuery|Component Where to put HTML. Default: body
callback? Function function(result).
insert? Boolean With false, replaces the content of the target. Default: true
preparator? Function function(response, output) changes the HTML before it is inserted.
Import and cache
<div id="target"></div>
<script>
IMPORTCACHE('/parts/hello.html', '5 minutes', '#target', function(result) {
	console.log(result, $('#target').text()); // 1 Hello
});
</script>
method

INC(path, [value], [delay], [reset])

Adds a number to the value on a path.
ParameterTypeDescription
path String The path of the value. See Paths.
value? Number The number to add. Default: 1
delay? Number A number of 10 or more delays the change by that many milliseconds. A smaller number is the change type: 1 manual, 2 input, 3 default.
reset? Boolean With true, the components on the path are also marked as not touched and not modified.

A missing value or a value that is not a number counts as 0.

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

inDOM(element)

Tells whether an element is inside the page body.
ParameterTypeDescription
element Element The element.

Returns Boolean true, or undefined when the element is outside the body.

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

isIE

true in Internet Explorer.
Read the value
console.log(typeof(isIE)); // boolean
property

isMOBILE

true on a mobile device.
Read the value
console.log(typeof(isMOBILE)); // boolean
property

isPRIVATEMODE

true when the browser storage is not available.
Read the value
console.log(typeof(isPRIVATEMODE)); // boolean
property

isROBOT

true when the user agent looks like a robot.
Read the value
console.log(typeof(isROBOT)); // boolean
property

isSTANDALONE

true when the page runs as an installed application.
Read the value
console.log(typeof(isSTANDALONE)); // boolean
property

isTOUCH

true on a device with a touch screen.
Read the value
console.log(typeof(isTOUCH)); // boolean
property

jComponent

Another name of MAIN. See MAIN.
Read the value
console.log(jComponent === MAIN); // true
method

LOCALIZE(text)

Adds translations to the dictionary.
ParameterTypeDescription
text String The translations.

Each line has the form key : value, and a line that starts with // is skipped. The values are stored in DEF.dictionary. The topic is explained in Localization.

Add translations
LOCALIZE('// Greetings\nhello : Ahoj');
console.log(DEF.dictionary.hello); // Ahoj
property

M

A short name of MAIN. See M.
Read the value
console.log(M === MAIN); // true
method

MACRO(name, declaration)

Declares a macro.
ParameterTypeDescription
name String The name of the macro.
declaration Function function(self, element, cls).

The topic is explained in Macros, and the object is described in Macro.

Declare a macro
MACRO('upper', function(self, element) {
	self.setter = value => element.text((value || '').toUpperCase());
});
console.log(typeof(M.macros.upper)); // function
property

MAIN

The main object of the library. See MAIN.
Read the value
console.log(MAIN.version); // 19.194
method

MAKE([target], fn, [update])

Builds an object in a function.
ParameterTypeDescription
target? Object|String An object or a path. Without it, a new object is created.
fn Function function(obj, path, set).
update? Boolean With false, an existing object on the path is written back without resetting its components. Default: true

Returns Object The object.

A string target is a path: the object on the path is changed, or a new one is created and written there. The function receives the object, the path and a function set(path, value).

Build an object
var obj = MAKE(function(o) {
	o.name = 'Peter';
});
console.log(obj); // {"name":"Peter"}
Build an object on a path
MAKE('user', function(o, path, set) {
	o.name = 'Peter';
	set('address.city', 'Bratislava');
});
console.log(GET('user')); // {"name":"Peter","address":{"city":"Bratislava"}}
method

MIDDLEWARE(name, fn)

Declares a middleware of routes. See Routing.
method

MODIFIED(path, [flags])

Lists the paths of the components that are touched and modified.
ParameterTypeDescription
path String The path, optionally with .* for everything below it.
flags? String|Array visible or hidden limits the search to those components.

Returns Array The paths of the modified components.

List the changed fields
ON('ready', function() {
	CHANGE('form.name');
	console.log(MODIFIED('form.*')); // ["form.name"]
});
property

MONTHS

The names of the months.
Read the value
console.log(MONTHS[11]); // December
property

NAV

The router object. See Routing.
method

NODEINDEXOF(element)

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

Returns Number The index.

Read the position
<ul><li>A</li><li id="b">B</li></ul>
<script>
console.log(NODEINDEXOF($('#b'))); // 1
</script>
method

NODEINSERT(element, target, [before])

Puts an element after or before another one.
ParameterTypeDescription
element Element|jQuery The element to move.
target Element|jQuery The reference element.
before? Boolean With true, puts it before the target.
Move an element
<ul><li id="a">A</li><li>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 by one position among its siblings.
ParameterTypeDescription
element Element|jQuery The element.
up? Boolean With true, moves it up. Otherwise it moves down.
Move an element up
<ul><li>A</li><li id="b">B</li></ul>
<script>
NODEMOVE($('#b'), true);
console.log($('ul').text()); // BA
</script>
method

NOOP()

A function that does nothing.
Use it as an empty callback
console.log(NOOP() === undefined); // true
method

NOTFOCUSED()

Tells whether the page is in the background.

Returns Boolean The result.

Check the page
console.log(typeof(NOTFOCUSED())); // boolean
method

NOTIFY(...paths)

Refreshes the components and watchers of exact paths.
ParameterTypeDescription
...paths String One or more paths.

Only components whose path is exactly the same are refreshed.

Notify a watcher
WATCH('user.name', function(path, value) {
	console.log(value); // Peter
});
window.user = { name: 'Peter' };
NOTIFY('user.name');
method

NOTMODIFIED(path, [value], [fields])

Tells whether a value is the same as the last time it was checked.
ParameterTypeDescription
path String The path, or any key when value is given.
value? Object The value to compare. Without it, the value of the path is used.
fields? Array Compares only these fields.

Returns Boolean true when the value has not changed.

The first check of a path returns false. The value is compared by a hash of its JSON form.

Skip work when nothing changed
console.log(NOTMODIFIED('list', [1, 2])); // false
console.log(NOTMODIFIED('list', [1, 2])); // true
console.log(NOTMODIFIED('list', [1, 2, 3])); // false
property

NOW

The current date, refreshed every minute.
Read the value
console.log(NOW instanceof Date); // true
method

NUL(path, [delay])

Writes null to a path.
ParameterTypeDescription
path String The path of the value. See Paths.
delay? Number A number of 10 or more delays the change by that many milliseconds. A smaller number is the change type: 1 manual, 2 input, 3 default.

NULL() is the same function.

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

NULL(path, [delay])

The same function as NUL().
Same function
console.log(NULL === NUL); // true
method

OFF(name, [path], [fn])

Removes handlers of an event.
ParameterTypeDescription
name String The name of the event.
path? String|Function The path, or the handler when no path is needed.
fn? Function The handler.

Several events can be separated by +. The form owner#name removes the handlers of that owner, and owner# removes all of them.

Remove a handler
var fn = () => console.log('never');
ON('ping', fn);
OFF('ping', fn);
console.log(EMIT('ping')); // false
Remove the handlers of an owner
ON('shop#ping', () => console.log('never'));
OFF('shop#');
console.log(EMIT('ping')); // false
method

ON(name, [path], fn, [init])

Registers a handler of an event.
ParameterTypeDescription
name String The name of the event.
path? String The path, for the event watch.
fn Function The handler.
init? Boolean With the event watch, the handler is also called immediately.

The name can list several events separated by a space or + . A name that starts with ^ puts the handler first. The form owner#name assigns the handler to an owner, so OFF() can remove it later. The name @flag myflag reacts to a custom flag on a path.

The event watch works like WATCH() and uses path and init. The events of the library are listed in Events.

Listen to a custom event
ON('cart.add', function(id, count) {
	console.log(id, count); // 15 2
});
EMIT('cart.add', 15, 2);
React to a custom flag
ON('@flag saved', function(path, value) {
	console.log(path, value); // user.name Peter
});
SET('user.name @saved', 'Peter');
method

OPT([obj], fn)

Builds an options object with nested paths.
ParameterTypeDescription
obj? Object The object to fill. Without it, a new object is created.
fn Function function(set, scope).

Returns Object The object.

The function receives set(path, value) and scope(prefix), which adds a prefix to the next paths.

Build options
var options = OPT(function(set, scope) {
	set('title', 'Users');
	scope('grid');
	set('limit', 20);
});
console.log(options); // {"title":"Users","grid":{"limit":20}}
method

PARSE(value, [date])

Parses JSON.
ParameterTypeDescription
value String The JSON or a selector.
date? Boolean Converts ISO dates to Date objects. Default: DEF.jsondate

Returns Object The value.

A string that starts with # or . is a selector of an element with JSON. Invalid JSON returns null, and an object is returned as it is.

Parse JSON
console.log(PARSE('{"id":5}').id); // 5
console.log(PARSE('{"d":"2024-01-01T10:00:00.000Z"}').d instanceof Date); // true
console.log(PARSE('wrong')); // null
method

PARSER(fn, [prepend])

Registers a global parser of component values.
ParameterTypeDescription
fn Function function(path, value, type, format).
prepend? Boolean With true, the parser runs first.

Returns Object The parsed value, when the function runs the parsers.

The function must always return the value. The built-in parser converts the types number, currency, float, boolean, bool, date and datetime. PARSER(value, path, type, [format]) runs all registered parsers.

Parse a value
console.log(PARSER('1 200.5', 'price', 'number')); // 1200.5
console.log(PARSER('on', 'active', 'boolean')); // true
method

PLUGIN(name, [fn], [init], [done])

Declares a plugin, or returns an existing one.
ParameterTypeDescription
name String The name of the plugin.
fn? Function function(exports).
init? Function|String Runs before the declaration. A string lists middleware names.
done? Function Called when the plugin is ready.

Returns Plugin The plugin.

The topic is explained in Plugins, and the object is described in Plugin.

Declare a plugin
PLUGIN('users', function(exports) {
	exports.count = 5;
});
setTimeout(function() {
	console.log(PLUGINS.users.count); // 5
}, 500);
method

PLUGINABLE(name, fn, [init])

Registers a plugin that is created by its first call.
ParameterTypeDescription
name String The name of the plugin.
fn Function|String The declaration or a URL.
init? Function|String Runs before the declaration.

The declaration can also be a URL of a file that declares the plugin.

Create a plugin on demand
PLUGINABLE('reports', function(exports) {
	exports.open = function() {
		console.log('opened'); // opened
	};
});
setTimeout(function() {
	console.log(PLUGINS.reports == null); // true
	EXEC('reports/open');
}, 500);
property

PLUGINS

An object with all created plugins, by name.
Read a plugin
PLUGIN('users', function(exports) {
	exports.limit = 10;
});
setTimeout(function() {
	console.log(Object.keys(PLUGINS)); // ["users"]
}, 500);
property

PREF

Stored user preferences. See PREF.
Read the value
PREF.set('theme', 'dark');
console.log(PREF.theme); // dark
method

PUSH(path, value, [delay], [reset])

Adds a value to the array on a path.
ParameterTypeDescription
path String The path of the value. See Paths.
value Object|Array The item or the items to add.
delay? Number A number of 10 or more delays the change by that many milliseconds. A smaller number is the change type: 1 manual, 2 input, 3 default.
reset? Boolean With true, the components on the path are also marked as not touched and not modified.

An array as the value adds each of its items. If the path holds no array, a new one is created. A path that starts with ^ adds to the beginning. As with SET(), the first argument can be a request and value the target path.

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

QUERIFY([url], obj)

Adds an object to a URL as a query string.
ParameterTypeDescription
url? String The URL, optionally with a method.
obj Object The values.

Returns String The URL.

Empty values are skipped, arrays are joined with a comma, and dates use the ISO format.

Build a URL
console.log(QUERIFY('GET /users/', { page: 2, tags: ['a', 'b'] })); // GET /users/?page=2&tags=a%2Cb
console.log(QUERIFY({ q: 'x y' })); // ?q=x%20y
method

QUEUE([name], fn)

Runs functions one after another.
ParameterTypeDescription
name? String The name of the queue.
fn Function function(next, pending).

Returns Number The number of waiting items.

The function receives next and the number of waiting items. The next item starts after next() is called.

Run in order
QUEUE('tasks', function(next) {
	setTimeout(next, 50);
});
QUEUE('tasks', function(next, pending) {
	console.log('second', pending); // second 0
	next();
});
method

RECONFIGURE(selector, value)

Changes the configuration of all matching components.
ParameterTypeDescription
selector String A selector as in FIND().
value Object|String The new configuration.
Change the configuration
ON('ready', function() {
	RECONFIGURE('box', { size: 10 });
	console.log(FIND('box').config.size); // 10
});
method

REDIRECT(url)

Navigates to a URL. See Routing.
method

REMOVECACHE(key)

Removes a value from the browser cache.
ParameterTypeDescription
key String The key.
Remove a value
CACHE('profile', 'Peter', '1 day');
REMOVECACHE('profile');
console.log(CACHE('profile') === undefined); // true
method

REPEAT([condition], process, delay, [init])

Runs a function repeatedly.
ParameterTypeDescription
condition? Function|String The condition.
process Function function(counter, scope).
delay Number The delay in milliseconds.
init? Boolean With true, the first run starts immediately.

The condition is a function or a path, and the run is skipped while it is not met. With the form path__expression, the expression receives the variable value. While the page is in the background, nothing runs unless DEF.repeatfocus is false.

Run every 100 ms
REPEAT(function(counter) {
	if (counter === 3)
		console.log('third run'); // third run
}, 100);
property

REPO

An empty object for your own shared data.
Read the value
REPO.items = [1, 2];
console.log(REPO.items.length); // 2
method

RESET(path, [delay])

Marks the components on a path as not touched and not modified, and validates them again.
ParameterTypeDescription
path String The path, optionally with .* for everything below it.
delay? Number A delay in milliseconds.
Reset a form
ON('ready', function() {
	SET('form.name', 'Peter');
	CHANGE('form.name');
	console.log(MODIFIED('form.*')); // ["form.name"]
	RESET('form.*');
	console.log(MODIFIED('form.*').length); // 0
});
method

RETURN(command, [multiple])

Reads a property of a component.
ParameterTypeDescription
command String The selector and the property.
multiple? Boolean With true, reads from all matching components.

Returns Object|Array The value, or an array with multiple.

The command has the form selector/property.

Read a property
ON('ready', function() {
	console.log(RETURN('box/title')); // Box
	console.log(RETURN('box/title', true)); // ["Box"]
});
method

REWRITE(path, value, [type])

Writes a value without refreshing components.
ParameterTypeDescription
path String The path of the value. See Paths.
value Object The new value.
type? Number The change type passed to watchers.

Data bindings and watchers still run. Use the @nowatch flag to skip the watchers.

Write without a component refresh
WATCH('user.name', function(path, value) {
	console.log(value); // Peter
});
REWRITE('user.name', 'Peter');
method

REWRITE2(path, value, [type])

Writes a value without refreshing components or data bindings.
ParameterTypeDescription
path String The path of the value. See Paths.
value Object The new value.
type? Number The change type passed to watchers.

Watchers still run.

Write without bindings
REWRITE2('user.name', 'Peter');
console.log(GET('user.name')); // Peter
method

ROUTE(url, fn, [middleware], [init])

Declares a route. See Routing.
method

SCROLLBAR(element, [options])

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

Returns Object The scrollbar.

The options:

OptionTypeDescription
orientationStringx or y. Without it, both directions
visibleX, visibleYBooleanKeeps the scrollbar visible
nativeBooleanUses the scrollbar of the browser
wrapBooleanWith false, the content is not wrapped
controlsjQueryThe element for the scrollbar controls
shadowBooleanAdds shadows at the edges
paddingNumberThe padding of the bars. Default 5
minsizeNumberThe smallest size of a bar. Default 50
thicknessNumberThe thickness of a bar. Default 10
margin, marginX, marginYNumberThe margins
offsetX, offsetYNumberAdded to the size of the view
parentString or ElementTakes the size from this parent
autoresizeBooleanWith false, the size is not checked on resize
intervalNumberThe interval of the size check
onscroll, onidle, onresizeFunctionHandlers that receive the scrollbar

The returned object has the methods scrollTop([value]), scrollLeft([value]), scrollBottom([value]), scrollRight([value]), scroll(x, y), resize(), check(), sync(element, [offset]), unsync() and destroy().

Create a scrollbar
<div id="box" style="height:100px"><div style="height:500px"></div></div>
<script>
var scrollbar = SCROLLBAR($('#box'), { orientation: 'y' });
console.log(typeof(scrollbar.scrollTop)); // function
console.log(M.scrollbars.length); // 1
</script>
method

SCROLLBARWIDTH()

Returns the width of the browser scrollbar in pixels.

Returns Number The width.

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

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

Calls a function or writes a value, depending on the target.
ParameterTypeDescription
target Function|String A function, a method or a path.
a? Object The first argument.
b? Object The second argument.
c? Object The third argument.
d? Object The fourth argument.

A function is called. A string with /, or a path that holds a function, goes to EXEC(). Any other string is a path, and the first argument is written to it.

Function or path
SEEX(value => console.log(value), 1); // 1
SEEX('result.value', 2);
console.log(GET('result.value')); // 2
method

SET(path, value, [delay], [reset])

Writes a value to a path and refreshes everything bound to it.
ParameterTypeDescription
path String The path of the value. See Paths.
value Object The new value.
delay? Number A number of 10 or more delays the change by that many milliseconds. A smaller number is the change type: 1 manual, 2 input, 3 default.
reset? Boolean With true, the components on the path are also marked as not touched and not modified.

Components, bindings and watchers on the path are refreshed. The third argument can also be true, which resets the state of the components right away.

A path that starts with + adds the value to an array like PUSH(). A path that starts with ~ merges it like EXT(). Flags can follow the path: see Flags and path modifiers.

When the first argument is a request such as GET /api/users/, the response is written to the path given as value.

Write a value
SET('user.name', 'Peter');
console.log(GET('user.name')); // Peter
console.log(GET('user')); // {"name":"Peter"}
Delay the write
SET('search', 'first', 100);
SET('search', 'second', 100);
setTimeout(function() {
	console.log(GET('search')); // second
}, 300);
Store a response
SET('GET /api/users/', 'users.response');
setTimeout(function() {
	console.log(GET('users.response.url')); // /api/users/
}, 200);
method

SETTER(selector, method, [...args])

Calls a method of all matching components.
ParameterTypeDescription
selector String A selector as in FIND().
method String The name of the method.
...args? Object The arguments of the method.

The selector and the method can be joined as selector/method. With true as the first argument, the call waits for the component. A selector that starts with ! does not start a lazy component.

Call a method
// The component logs 'Hello ' + name
ON('ready', function() {
	SETTER('box', 'hello', 'Peter');
	SETTER('box/hello', 'Anna');
});
method

setTimeout2(name, fn, delay, [limit], [arg])

Starts a named timer and cancels the previous timer of the same name.
ParameterTypeDescription
name String The name of the timer.
fn Function The function.
delay Number The delay in milliseconds.
limit? Number How many times the timer can be postponed.
arg? Object The argument of the function.

Returns String The name of the timer.

With a limit, the timer is postponed at most that many times, so the function still runs during constant calls.

Keep only the last call
function search(value) {
	console.log(value); // last
}
setTimeout2('search', search, 50, null, 'first');
setTimeout2('search', search, 50, null, 'last');
method

STOPDEBUG()

Keeps pausing the browser debugger while the developer tools are open.

The function repeats itself every 5 seconds and cannot be stopped.

method

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

Serializes a value to JSON.
ParameterTypeDescription
value Object The value.
compress? Boolean Compresses the output. Default: DEF.jsoncompress
fields? Array|Object|Function An array of allowed fields, an object with field: false, or function(key, value).
encrypt? Boolean Encrypts the output with the key from DEF.secret().

Returns String The JSON.

Compression trims strings and removes empty strings, false and null.

Serialize a value
console.log(STRINGIFY({ a: 1, b: '', c: false }, true)); // {"a":1}
console.log(STRINGIFY({ a: 1, b: 2 }, false, ['b'])); // {"b":2}
method

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

Adds CSS to the page.
ParameterTypeDescription
value String|Array The CSS.
id? String The identifier of the style. The element gets the id css plus this value.
selector? String A selector that wraps the rules.

An existing style with the same identifier is replaced. A selector is added before every rule. CSS() is the same function.

Add scoped CSS
STYLE('b { color: red }', 'mystyle', '#panel');
console.log($('#cssmystyle').html()); // #panel b{ color: red }
property

Ta

A short name of Tangular.
Read the value
console.log(Ta === Tangular); // true
property

Tangular

The template engine. See Templates with Tangular.
Read the value
console.log(Tangular.render('Hello {{ name }}', { name: 'Peter' })); // Hello Peter
method

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

Calls an API with DAPI() when DEF.api is set, and with WAPI() otherwise.
ParameterTypeDescription
name String The name of the schema.
data? Object The data.
callback? Function|String function(response, err, output), or a path.

Returns Object|Promise The result of the selected function.

Select the transport
DEF.api = '/api/';
TAPI('users_list', null, function(response) {
	console.log(response.url); // /api/
});
property

TEMP

An object for temporary data.

The library replaces it with an empty object every five minutes.

Read the value
TEMP.value = 5;
console.log(TEMP.value); // 5
property

Thelpers

The helpers of the template engine. See Tangular helpers.
Read the value
console.log(typeof(Thelpers)); // object
method

TOGGLE(path, [delay], [reset])

Writes the opposite boolean value to a path.
ParameterTypeDescription
path String The path of the value. See Paths.
delay? Number A number of 10 or more delays the change by that many milliseconds. A smaller number is the change type: 1 manual, 2 input, 3 default.
reset? Boolean With true, the components on the path are also marked as not touched and not modified.
Switch a value
SET('menu.open', false);
TOGGLE('menu.open');
console.log(GET('menu.open')); // true
method

TRANSLATE(text)

Replaces every @(text) with its translation.
ParameterTypeDescription
text String The text.

Returns String The translated text.

The key in DEF.dictionary is HASH(text).toString(36), optionally with the prefix T. Text without a translation stays in the original language.

Translate text
DEF.dictionary[HASH('Hello').toString(36)] = 'Ahoj';
console.log(TRANSLATE('@(Hello), @(Peter)')); // Ahoj, Peter
method

UNAUTHORIZED(...roles)

Tells whether the current user lacks all of the given roles.
ParameterTypeDescription
...roles String The roles.

Returns Boolean true when the user has none of the roles.

The user is read from window.user. The fields sa and su allow everything, and the roles come from permissions or roles, as an array or an object.

Check a role
window.user = { roles: ['editor'] };
console.log(UNAUTHORIZED('editor')); // false
console.log(UNAUTHORIZED('admin')); // true
method

UNWATCH(path, [fn])

Removes a watcher.
ParameterTypeDescription
path String The watched path.
fn? Function The function given to WATCH().

Without a function, all watchers of the path are removed.

Stop watching
var count = 0;
var fn = () => count++;
WATCH('value', fn);
SET('value', 1);
UNWATCH('value', fn);
SET('value', 2);
console.log(count); // 1
method

UPD(path, [delay], [reset])

Tells the library that the value on a path has changed.
ParameterTypeDescription
path String The path of the value. See Paths.
delay? Number A number of 10 or more delays the change by that many milliseconds. A smaller number is the change type: 1 manual, 2 input, 3 default.
reset? Boolean With true, the components on the path are also marked as not touched and not modified.

Use it after changing an object directly. Components are refreshed and watchers are called. UPDATE() is the same function. The second argument can also be true, which resets the state of the components.

Refresh after a direct change
SET('user', { name: 'Peter' });
WATCH('user.name', function(path, value) {
	console.log(value); // Anna
});
GET('user').name = 'Anna';
UPD('user.name');
method

UPDATE(path, [delay], [reset])

The same function as UPD().
Same function
console.log(UPDATE === UPD); // true
method

UPLOAD(url, data, [callback], [delay], [progress])

Uploads data to a server.
ParameterTypeDescription
url String The URL, optionally with a method.
data FormData|Object The data.
callback? Function|String function(response, err, output), or a path.
delay? Number Waits this many milliseconds before sending.
progress? Function|String function(percentage), or a path.

Returns Promise Only when no callback is given.

The default method is POST. FormData is sent as it is, and anything else as JSON. Without a callback, the function returns a Promise. progress can be the fourth argument when no delay is needed.

Upload a file
var data = new FormData();
data.append('name', 'photo.jpg');
UPLOAD('/api/upload/', data, function(response) {
	console.log(response.url); // /api/upload/
});
method

VALID(path, [flags])

Tells whether no component on a path is invalid.
ParameterTypeDescription
path String The path, optionally with .* for everything below it.
flags? String|Array visible or hidden limits the check to those components.

Returns Boolean The result.

Unlike CAN(), it does not look at whether the components are touched.

Check a form
ON('ready', function() {
	console.log(VALID('form.*')); // false
	SET('form', { name: 'Peter', age: 30 });
	console.log(VALID('form.*')); // true
});
method

VBIND(html)

Creates a virtual binder from HTML.
ParameterTypeDescription
html String The HTML with bindings.

Returns VBinder The virtual binder.

The object is described in Virtual binder, and the topic in Virtual bindings.

Bind a detached element
var binder = VBIND('<div><span data-bind="name__text"></span></div>');
binder.set({ name: 'Peter' });
console.log(binder.element.find('span').text()); // Peter
method

VBINDARRAY(html, element)

Renders an array with a virtual binder for each item.
ParameterTypeDescription
html String The HTML of one item.
element Element|jQuery|Component The parent element.

Returns Object An object with the methods set(), get(), upd() and remove().

The topic is explained in Virtual bindings.

Render a list
<ul id="list"></ul>
<script>
var list = VBINDARRAY('<li data-bind="name__text"></li>', $('#list'));
list.set([{ name: 'Peter' }, { name: 'Anna' }]);
console.log($('#list').text()); // PeterAnna
</script>
method

VERSION(...items)

Selects the version of components that are used without a version.
ParameterTypeDescription
...items String The components and their versions.

Each item has the form name@version, and one string can list several items separated by a comma.

Select a version
<ui-component name="tag"></ui-component>
<script>
COMPONENT('tag@2', function(self) {
	self.make = () => self.element.text('two');
});
VERSION('tag@2');
ON('ready', function() {
	console.log($('ui-component').text()); // two
});
</script>
method

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

Tells whether an element is in the visible height of the window.
ParameterTypeDescription
element Element|jQuery The element.
threshold? Number A margin in pixels. Default: 0
mode? String visible, above or below. Default: visible

Returns Boolean The result.

Check an element
<div id="box">Box</div>
<script>
console.log(VISIBLE($('#box'))); // true
</script>
property

W

A short name of window.
Read the value
console.log(W === window); // true
method

WAIT(condition, callback, [interval], [timeout])

Waits until a condition is met.
ParameterTypeDescription
condition Function|String The function or the path to check.
callback Function function(err, again).
interval? Number The interval of the checks in milliseconds. Default: 500
timeout? Number The longest wait in milliseconds.

The condition is a function or a path. The callback receives an error after a timeout, and a function that starts the wait again. Without a timeout, the wait never ends by itself.

Wait for a value
WAIT('app.ready', function() {
	console.log(GET('app.ready')); // true
}, 50);
setTimeout(() => SET('app.ready', true), 100);
Stop after a timeout
WAIT(() => false, function(err) {
	console.log(err.message); // Timeout.
}, 50, 200);
method

WAPI([name], [data], [callback], [timeout])

Calls an API over the WebSocket connection.
ParameterTypeDescription
name? String|Object The name of the schema, or the connection options.
data? Object The data.
callback? Function|String function(response, err, output), or a path.
timeout? Number The timeout in milliseconds. Default: 10000

Returns Object|Promise The connection, or a Promise.

An object as the first argument opens the connection like WAPI_INIT(). Without arguments, the function returns the open connection. Without a callback, it returns a Promise. The default timeout of a call is 10 seconds.

Call over a socket
WAPI({ url: '/api/' });
WAPI('users_list', null, function(response) {
	console.log(response.schema); // users_list
});
method

WAPI_INIT(options)

Opens the WebSocket connection used by WAPI().
ParameterTypeDescription
options Object The connection options.

Returns Object The options object with the added methods.

The options are url, reconnect (a delay in milliseconds, or false), expire (reconnects after this time), callback (called once after the first connection attempt), and the handlers open, close(e) and message(data).

The returned object has the methods send(name, data, callback, [timeout]), on(name, fn) for the events open, close, message and reconnect, emit(name, ...) and pause(is).

Open a connection
WAPI_INIT({
	url: '/api/',
	open: function() {
		console.log('connected'); // connected
	}
});
console.log(typeof(WAPI().send)); // function
method

WARN(...args)

Writes a warning to the console.
ParameterTypeDescription
...args Object The values to write.
Write a warning
WARN('Disk is full');
console.log(typeof(WARN)); // function
method

WATCH(path, fn, [init])

Calls a function when the value on a path changes.
ParameterTypeDescription
path String The path to watch.
fn Function function(path, value, type).
init? Boolean With true, the function is also called immediately.

The function receives the changed path, the value and the change type: 0 initial call, 1 manual, 2 input, 3 default. A path of users.* also reacts to everything below users. Several paths can be separated by a space, and a path that starts with ^ runs before the other watchers.

React to a change
WATCH('user.name', function(path, value, type) {
	console.log(path, value, type); // user.name Peter 1
});
SET('user.name', 'Peter');
Call it immediately
SET('count', 5);
WATCH('count', function(path, value, type) {
	console.log(value, type); // 5 0
}, true);
method

WATCHONCE(path, fn)

Calls a function on the next change of a path only.
ParameterTypeDescription
path String The path to watch.
fn Function function(path, value, type).
React once
WATCHONCE('count', function(path, value) {
	console.log(value); // 1
});
SET('count', 1);
SET('count', 2);
property

WH

The height of the window in pixels.
Read the value
console.log(typeof(WH)); // number
method

WIDTH([element])

Returns the display size of the window or an element.
ParameterTypeDescription
element? jQuery The element. Default: window

Returns String xs, sm, md or lg.

The limits are in DEF.devices.

Read the size of an element
<div id="box" style="width:1000px"></div>
<script>
console.log(WIDTH($('#box'))); // md
</script>
method

WORKFLOW(declaration, [tasks], [callback])

Runs named steps that hand over a value.
ParameterTypeDescription
declaration Function function($).
tasks? Object The steps by name.
callback? Function function(value, err, $).

Returns Object The workflow.

The object passed to the declaration and to every step has these members:

MemberDescription
push(name, fn)Adds a step: function($, value)
next(name, [value])Runs a step. An unknown name ends the workflow
next2(name)Returns a callback that runs the step
done([value])Calls the final callback with the value
invalid(err)Reports an error to error or to the final callback
callback(fn)Replaces the final callback
clone()Creates a workflow with the same steps
destroy()Ends the workflow
value, current, prevThe value, the current step and the previous step
Run two steps
WORKFLOW(function($) {
	$.push('load', ($, value) => $.next('save', value + 1));
	$.push('save', ($, value) => $.done(value * 2));
	$.next('load', 1);
}, function(value) {
	console.log(value); // 4
});
property

WW

The width of the window in pixels.
Read the value
console.log(typeof(WW)); // number
Made in Europe