Global functions
The functions and objects that jComponent adds to the window object.
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.
ACMD(name, [...args])| Parameter | Type | Description |
|---|---|---|
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.
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.
ADAPT(path, id, text)| Parameter | Type | Description |
|---|---|---|
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.
console.log(ADAPT('users', 'form1', '~PATH~ and ~ID~')); // users and form1
method
ADD(value, [element], [config], [content])
Adds a component to the page.
ADD(value, [element], [config], [content])| Parameter | Type | Description |
|---|---|---|
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('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.
AEXEC(path, [...args])| Parameter | Type | Description |
|---|---|---|
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.
window.save = value => console.log(value); // 5
AEXEC('save')(5);
method
AJAX(url, [data], [callback], [delay])
Sends an HTTP request.
AJAX(url, [data], [callback], [delay])| Parameter | Type | Description |
|---|---|---|
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:
| Item | Meaning |
|---|---|
!METHOD | Sends cookies with the request |
{ "Name": "value" } | Request headers |
<5 minutes> | Caches the response, as in AJAXCACHE() |
(name) | Applies the settings from AJAXCONFIG() |
repeat | Repeats the request when the server is not available |
cancel | Cancels the previous unfinished request to the same URL |
urlencoded | Sends the data as a URL-encoded form |
json | Accepts only a JSON response |
error | Passes the response through ERROR() |
noencrypt, nodecrypt, nocsrf | Skips encryption, decryption or the CSRF header |
#id | Names the request for cancel, or waits for a code list |
@flag | Emits 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.
AJAX('POST /api/users/', { name: 'Peter' }, function(response, err) {
console.log(response.method, response.url); // POST /api/users/
console.log(response.body); // {"name":"Peter"}
});
(async function() {
var response = await AJAX('GET /api/users/');
console.log(response.url); // /api/users/
})();
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.
AJAXCACHE(url, [data], callback, expire, [delay], [clear])| Parameter | Type | Description |
|---|---|---|
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.
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.
AJAXCACHEREVIEW(url, [data], callback, expire, [delay], [clear])| Parameter | Type | Description |
|---|---|---|
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.
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.
AJAXCONFIG(name, fn)| Parameter | Type | Description |
|---|---|---|
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.
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.
API(url, [data], [callback])| Parameter | Type | Description |
|---|---|---|
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.
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.
APPEARANCE(options)| Parameter | Type | Description |
|---|---|---|
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.
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.
ASETTER(selector, method, [...args])| Parameter | Type | Description |
|---|---|---|
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.
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.
ATTRD(element, [name])| Parameter | Type | Description |
|---|---|---|
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.
<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.
BIND(path)| Parameter | Type | Description |
|---|---|---|
path |
String|Array |
One path or a list of paths. |
<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.
BLOCKED(name, timeout, [callback])| Parameter | Type | Description |
|---|---|---|
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.
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.
CACHE(key, [value], [expire])| Parameter | Type | Description |
|---|---|---|
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.
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.
CACHEPATH(path, expire, [rebind])| Parameter | Type | Description |
|---|---|---|
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.
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.
CAN(path, [flags])| Parameter | Type | Description |
|---|---|---|
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.
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.
CHANGE(path, [value])| Parameter | Type | Description |
|---|---|---|
path |
String |
The path of the value. See Paths. |
value? |
Boolean |
With false, the marks are removed. Default: true |
ON('ready', function() {
CHANGE('form.age');
console.log(MODIFIED('form.*')); // ["form.age"]
});
method
CL(name, callback)
Waits until code lists are loaded.
CL(name, callback)| Parameter | Type | Description |
|---|---|---|
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.
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.
CL_INIT(name, source, [expire], [init])| Parameter | Type | Description |
|---|---|---|
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. |
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.
clearTimeout2(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the timer. |
Returns Boolean true when a timer was running.
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().
CLINIT(name, source, [expire], [init])console.log(CLINIT === CL_INIT); // true
method
CLONE(value, [nopath])
Creates a deep copy of a value.
CLONE(value, [nopath])| Parameter | Type | Description |
|---|---|---|
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.
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.
CLRELOAD(name, [callback])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the code list. |
callback? |
Function |
Runs when the lists are loaded. |
Several names can be separated by a comma.
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.
CMD(name, [a], [b], [c], [d], [e])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the command. |
a? |
Object |
Up to five arguments, a to e. |
Components register commands with self.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.
COMPILE([container])| Parameter | Type | Description |
|---|---|---|
container? |
Element|jQuery |
Limits the search to this element. |
Call it after adding HTML by hand.
$(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.
COMPONENT(name, [config], declaration, [dependencies])| Parameter | Type | Description |
|---|---|---|
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.
<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.
COMPONENTS(path)| Parameter | Type | Description |
|---|---|---|
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.
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.
CONFIG(selector, config)| Parameter | Type | Description |
|---|---|---|
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.
CONFIG('box', { size: 10 });
ON('ready', function() {
console.log(FIND('box').config.size); // 10
});
property
COOKIES
An object for reading and writing cookies.
COOKIESIt has the methods get(name), set(name, value, expire, [samesite]) and rem(name). expire is a Date or a value such as 1 day.
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.
COPY(source, target)| Parameter | Type | Description |
|---|---|---|
source |
Object |
The object to read. |
target |
Object |
The object to write. |
Returns Object The target object.
Objects inside the source are cloned.
var target = COPY({ a: 1 }, { b: 2 });
console.log(target); // {"b":2,"a":1}
method
CSS(value, [id], [selector])
The same function as STYLE().
CSS(value, [id], [selector])console.log(CSS === STYLE); // true
method
DAPI(name, [data], [callback])
Calls the API endpoint set in DEF.api.
DAPI(name, [data], [callback])| Parameter | Type | Description |
|---|---|---|
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().
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.
DAYSconsole.log(DAYS[0]); // Sunday
method
DEBUG()
Turns on the debug mode.
DEBUG()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.
DEBUG();
EXEC('missing.method');
console.log('done'); // done
method
DECRYPT(value, [key], [type])
Decodes a value from ENCRYPT().
DECRYPT(value, [key], [type])| Parameter | Type | Description |
|---|---|---|
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.
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.
DEFconsole.log(DEF.delay); // 555
method
DEFAULT(path, [delay], [reset])
Restores the default values of the components on a path.
DEFAULT(path, [delay], [reset])| Parameter | Type | Description |
|---|---|---|
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.
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.
DIFFDOM(element, selector, html, [attribute])| Parameter | Type | Description |
|---|---|---|
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.
<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().
DISABLED(path, [flags])| Parameter | Type | Description |
|---|---|---|
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.
ON('ready', function() {
console.log(DISABLED('form.*')); // true
});
method
EMIT(name, [...args])
Calls the handlers of an event.
EMIT(name, [...args])| Parameter | Type | Description |
|---|---|---|
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').
ON('hello', name => console.log(name)); // Peter
console.log(EMIT('hello', 'Peter')); // true
console.log(EMIT('unknown')); // false
property
EMPTYARRAY
A frozen empty array.
EMPTYARRAYconsole.log(Object.isFrozen(EMPTYARRAY)); // true
property
EMPTYOBJECT
A frozen empty object.
EMPTYOBJECTconsole.log(Object.isFrozen(EMPTYOBJECT)); // true
method
ENCRYPT(value, [key], [type])
Encodes a value into a hexadecimal string signed with a key.
ENCRYPT(value, [key], [type])| Parameter | Type | Description |
|---|---|---|
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.
var token = ENCRYPT({ id: 5 }, 'secret');
console.log(DECRYPT(token, 'secret')); // {"id":5}
method
ENV(name, [value])
Reads or writes an environment variable.
ENV(name, [value])| Parameter | Type | Description |
|---|---|---|
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.
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.
ENVIRONMENT(name, [version], [language], [env])| Parameter | Type | Description |
|---|---|---|
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.
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.
ERROR(value, [success], [error])| Parameter | Type | Description |
|---|---|---|
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.
console.log(ERROR([{ error: 'Invalid name' }])); // true
console.log(ERROR({ id: 5 })); // false
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.
ERRORS(path, [flags], [highlight])| Parameter | Type | Description |
|---|---|---|
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.
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.
EVALUATE(path, expression, [nopath])| Parameter | Type | Description |
|---|---|---|
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.
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().
EXE([wait], path, [...args])console.log(EXE === EXEC); // true
method
EXEC([wait], path, [...args])
Calls a function, a plugin method, a component method, a command or an event.
EXEC([wait], path, [...args])| Parameter | Type | Description |
|---|---|---|
wait? |
Boolean |
With true, waits for the target. |
path |
String |
The target. |
...args? |
Object |
The arguments. |
The form of the path selects the target:
| Path | Target |
|---|---|
plugin/method | A method of a plugin |
@plugin.method | A method of a plugin |
path.to.fn | A function on a path |
#name | The event name |
-selector/method | A method of a component, as in SETTER() |
&name | A command, as in CMD() |
With true as the first argument, the call waits until the target exists. EXE() is the same function.
PLUGIN('users', function(exports) {
exports.hello = function(name) {
console.log(name); // Peter
};
});
EXEC(true, 'users/hello', 'Peter');
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.
EXT(path, value, [delay], [reset])| Parameter | Type | Description |
|---|---|---|
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.
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().
EXTEND(path, value, [delay], [reset])console.log(EXTEND === EXT); // true
method
EXTENSION(name, [config], declaration)
Extends a component or a plugin.
EXTENSION(name, [config], declaration)| Parameter | Type | Description |
|---|---|---|
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.
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.
FIND(selector, [many], [nocache], [callback])| Parameter | Type | Description |
|---|---|---|
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.
ON('ready', function() {
console.log(FIND('box').path); // data.box
console.log(FIND('.data.box').name); // box
console.log(FIND('box', true).length); // 1
});
FIND('box', function(com) {
console.log(com.name); // box
});
method
FN(expression)
Creates a function from a string.
FN(expression)| Parameter | Type | Description |
|---|---|---|
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.
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.
FORMATTER(fn, [prepend])| Parameter | Type | Description |
|---|---|---|
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.
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.
FREE([delay])| Parameter | Type | Description |
|---|---|---|
delay? |
Number |
The delay in milliseconds. Default: 10 |
The library also does this every three minutes.
FREE();
console.log(typeof(FREE)); // function
property
FUNC
An empty object for your own shared functions.
FUNCFUNC.sum = (a, b) => a + b;
console.log(FUNC.sum(1, 2)); // 3
method
GET(path, [scope])
Reads the value of a path.
GET(path, [scope])| Parameter | Type | Description |
|---|---|---|
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.
SET('user', { name: 'Peter', age: 30 });
console.log(GET('user.age')); // 30
console.log(GET('name', { name: 'Anna' })); // Anna
GET('settings.theme', function(value) {
console.log(value); // dark
});
setTimeout(() => SET('settings.theme', 'dark'), 100);
method
GUID([size])
Creates a random identifier.
GUID([size])| Parameter | Type | Description |
|---|---|---|
size? |
Number |
The length. Without it, the identifier has 36 characters in the form of a UUID. |
Returns String The identifier.
console.log(GUID().length); // 36
console.log(GUID(10).length); // 10
method
HASH(value, [unsigned])
Creates a number from a value.
HASH(value, [unsigned])| Parameter | Type | Description |
|---|---|---|
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.
console.log(HASH('abc')); // 96354
method
IMPORT(url, [target], [callback], [insert], [preparator])
Loads a script, a style or HTML into the page.
IMPORT(url, [target], [callback], [insert], [preparator])| Parameter | Type | Description |
|---|---|---|
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.
<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.
IMPORTCACHE(url, expire, [target], [callback], [insert], [preparator])| Parameter | Type | Description |
|---|---|---|
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. |
<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.
INC(path, [value], [delay], [reset])| Parameter | Type | Description |
|---|---|---|
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.
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.
inDOM(element)| Parameter | Type | Description |
|---|---|---|
element |
Element |
The element. |
Returns Boolean true, or undefined when the element is outside the body.
console.log(inDOM(document.body)); // true
console.log(inDOM(document.createElement('div')) === undefined); // true
property
isIE
true in Internet Explorer.
isIEconsole.log(typeof(isIE)); // boolean
property
isMOBILE
true on a mobile device.
isMOBILEconsole.log(typeof(isMOBILE)); // boolean
property
isPRIVATEMODE
true when the browser storage is not available.
isPRIVATEMODEconsole.log(typeof(isPRIVATEMODE)); // boolean
property
isROBOT
true when the user agent looks like a robot.
isROBOTconsole.log(typeof(isROBOT)); // boolean
property
isSTANDALONE
true when the page runs as an installed application.
isSTANDALONEconsole.log(typeof(isSTANDALONE)); // boolean
property
isTOUCH
true on a device with a touch screen.
isTOUCHconsole.log(typeof(isTOUCH)); // boolean
property
jComponent
Another name of MAIN. See MAIN.
jComponentconsole.log(jComponent === MAIN); // true
method
LOCALIZE(text)
Adds translations to the dictionary.
LOCALIZE(text)| Parameter | Type | Description |
|---|---|---|
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.
LOCALIZE('// Greetings\nhello : Ahoj');
console.log(DEF.dictionary.hello); // Ahoj
property
M
A short name of MAIN. See M.
Mconsole.log(M === MAIN); // true
method
MACRO(name, declaration)
Declares a macro.
MACRO(name, declaration)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the macro. |
declaration |
Function |
function(self, element, cls). |
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.
MAINconsole.log(MAIN.version); // 19.194
method
MAKE([target], fn, [update])
Builds an object in a function.
MAKE([target], fn, [update])| Parameter | Type | Description |
|---|---|---|
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).
var obj = MAKE(function(o) {
o.name = 'Peter';
});
console.log(obj); // {"name":"Peter"}
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.
MIDDLEWARE(name, fn)
method
MODIFIED(path, [flags])
Lists the paths of the components that are touched and modified.
MODIFIED(path, [flags])| Parameter | Type | Description |
|---|---|---|
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.
ON('ready', function() {
CHANGE('form.name');
console.log(MODIFIED('form.*')); // ["form.name"]
});
property
MONTHS
The names of the months.
MONTHSconsole.log(MONTHS[11]); // December
method
NODEINDEXOF(element)
Returns the position of an element among its siblings.
NODEINDEXOF(element)| Parameter | Type | Description |
|---|---|---|
element |
Element|jQuery |
The element. |
Returns Number The index.
<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.
NODEINSERT(element, target, [before])| Parameter | Type | Description |
|---|---|---|
element |
Element|jQuery |
The element to move. |
target |
Element|jQuery |
The reference element. |
before? |
Boolean |
With true, puts it before the target. |
<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.
NODEMOVE(element, [up])| Parameter | Type | Description |
|---|---|---|
element |
Element|jQuery |
The element. |
up? |
Boolean |
With true, moves it up. Otherwise it moves down. |
<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.
NOOP()console.log(NOOP() === undefined); // true
method
NOTFOCUSED()
Tells whether the page is in the background.
NOTFOCUSED()Returns Boolean The result.
console.log(typeof(NOTFOCUSED())); // boolean
method
NOTIFY(...paths)
Refreshes the components and watchers of exact paths.
NOTIFY(...paths)| Parameter | Type | Description |
|---|---|---|
...paths |
String |
One or more paths. |
Only components whose path is exactly the same are refreshed.
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.
NOTMODIFIED(path, [value], [fields])| Parameter | Type | Description |
|---|---|---|
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.
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.
NOWconsole.log(NOW instanceof Date); // true
method
NUL(path, [delay])
Writes null to a path.
NUL(path, [delay])| Parameter | Type | Description |
|---|---|---|
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.
SET('user.name', 'Peter');
NUL('user.name');
console.log(GET('user.name')); // null
method
NULL(path, [delay])
The same function as NUL().
NULL(path, [delay])console.log(NULL === NUL); // true
method
OFF(name, [path], [fn])
Removes handlers of an event.
OFF(name, [path], [fn])| Parameter | Type | Description |
|---|---|---|
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.
var fn = () => console.log('never');
ON('ping', fn);
OFF('ping', fn);
console.log(EMIT('ping')); // false
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.
ON(name, [path], fn, [init])| Parameter | Type | Description |
|---|---|---|
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.
ON('cart.add', function(id, count) {
console.log(id, count); // 15 2
});
EMIT('cart.add', 15, 2);
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.
OPT([obj], fn)| Parameter | Type | Description |
|---|---|---|
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.
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.
PARSE(value, [date])| Parameter | Type | Description |
|---|---|---|
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.
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.
PARSER(fn, [prepend])| Parameter | Type | Description |
|---|---|---|
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.
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.
PLUGIN(name, [fn], [init], [done])| Parameter | Type | Description |
|---|---|---|
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.
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.
PLUGINABLE(name, fn, [init])| Parameter | Type | Description |
|---|---|---|
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.
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.
PLUGINSPLUGIN('users', function(exports) {
exports.limit = 10;
});
setTimeout(function() {
console.log(Object.keys(PLUGINS)); // ["users"]
}, 500);
property
PREF
Stored user preferences. See PREF.
PREFPREF.set('theme', 'dark');
console.log(PREF.theme); // dark
method
PUSH(path, value, [delay], [reset])
Adds a value to the array on a path.
PUSH(path, value, [delay], [reset])| Parameter | Type | Description |
|---|---|---|
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.
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.
QUERIFY([url], obj)| Parameter | Type | Description |
|---|---|---|
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.
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.
QUEUE([name], fn)| Parameter | Type | Description |
|---|---|---|
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.
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.
RECONFIGURE(selector, value)| Parameter | Type | Description |
|---|---|---|
selector |
String |
A selector as in FIND(). |
value |
Object|String |
The new configuration. |
ON('ready', function() {
RECONFIGURE('box', { size: 10 });
console.log(FIND('box').config.size); // 10
});
method
REDIRECT(url)
Navigates to a URL. See Routing.
REDIRECT(url)
method
REMOVECACHE(key)
Removes a value from the browser cache.
REMOVECACHE(key)| Parameter | Type | Description |
|---|---|---|
key |
String |
The key. |
CACHE('profile', 'Peter', '1 day');
REMOVECACHE('profile');
console.log(CACHE('profile') === undefined); // true
method
REPEAT([condition], process, delay, [init])
Runs a function repeatedly.
REPEAT([condition], process, delay, [init])| Parameter | Type | Description |
|---|---|---|
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.
REPEAT(function(counter) {
if (counter === 3)
console.log('third run'); // third run
}, 100);
property
REPO
An empty object for your own shared data.
REPOREPO.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.
RESET(path, [delay])| Parameter | Type | Description |
|---|---|---|
path |
String |
The path, optionally with .* for everything below it. |
delay? |
Number |
A delay in milliseconds. |
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.
RETURN(command, [multiple])| Parameter | Type | Description |
|---|---|---|
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.
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.
REWRITE(path, value, [type])| Parameter | Type | Description |
|---|---|---|
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.
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.
REWRITE2(path, value, [type])| Parameter | Type | Description |
|---|---|---|
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.
REWRITE2('user.name', 'Peter');
console.log(GET('user.name')); // Peter
method
ROUTE(url, fn, [middleware], [init])
Declares a route. See Routing.
ROUTE(url, fn, [middleware], [init])
method
SCROLLBAR(element, [options])
Adds a custom scrollbar to an element.
SCROLLBAR(element, [options])| Parameter | Type | Description |
|---|---|---|
element |
jQuery |
The element. |
options? |
Object |
The options. |
Returns Object The scrollbar.
The options:
| Option | Type | Description |
|---|---|---|
orientation | String | x or y. Without it, both directions |
visibleX, visibleY | Boolean | Keeps the scrollbar visible |
native | Boolean | Uses the scrollbar of the browser |
wrap | Boolean | With false, the content is not wrapped |
controls | jQuery | The element for the scrollbar controls |
shadow | Boolean | Adds shadows at the edges |
padding | Number | The padding of the bars. Default 5 |
minsize | Number | The smallest size of a bar. Default 50 |
thickness | Number | The thickness of a bar. Default 10 |
margin, marginX, marginY | Number | The margins |
offsetX, offsetY | Number | Added to the size of the view |
parent | String or Element | Takes the size from this parent |
autoresize | Boolean | With false, the size is not checked on resize |
interval | Number | The interval of the size check |
onscroll, onidle, onresize | Function | Handlers 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().
<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.
SCROLLBARWIDTH()Returns Number 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.
SEEX(target, [a], [b], [c], [d])| Parameter | Type | Description |
|---|---|---|
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.
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.
SET(path, value, [delay], [reset])| Parameter | Type | Description |
|---|---|---|
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.
SET('user.name', 'Peter');
console.log(GET('user.name')); // Peter
console.log(GET('user')); // {"name":"Peter"}
SET('search', 'first', 100);
SET('search', 'second', 100);
setTimeout(function() {
console.log(GET('search')); // second
}, 300);
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.
SETTER(selector, method, [...args])| Parameter | Type | Description |
|---|---|---|
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.
// 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.
setTimeout2(name, fn, delay, [limit], [arg])| Parameter | Type | Description |
|---|---|---|
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.
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.
STOPDEBUG()The function repeats itself every 5 seconds and cannot be stopped.
method
STRINGIFY(value, [compress], [fields], [encrypt])
Serializes a value to JSON.
STRINGIFY(value, [compress], [fields], [encrypt])| Parameter | Type | Description |
|---|---|---|
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.
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.
STYLE(value, [id], [selector])| Parameter | Type | Description |
|---|---|---|
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.
STYLE('b { color: red }', 'mystyle', '#panel');
console.log($('#cssmystyle').html()); // #panel b{ color: red }
property
Ta
A short name of Tangular.
Taconsole.log(Ta === Tangular); // true
property
Tangular
The template engine. See Templates with Tangular.
Tangularconsole.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.
TAPI(name, [data], [callback])| Parameter | Type | Description |
|---|---|---|
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.
DEF.api = '/api/';
TAPI('users_list', null, function(response) {
console.log(response.url); // /api/
});
property
TEMP
An object for temporary data.
TEMPThe library replaces it with an empty object every five minutes.
TEMP.value = 5;
console.log(TEMP.value); // 5
property
Thelpers
The helpers of the template engine. See Tangular helpers.
Thelpersconsole.log(typeof(Thelpers)); // object
method
TOGGLE(path, [delay], [reset])
Writes the opposite boolean value to a path.
TOGGLE(path, [delay], [reset])| Parameter | Type | Description |
|---|---|---|
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. |
SET('menu.open', false);
TOGGLE('menu.open');
console.log(GET('menu.open')); // true
method
TRANSLATE(text)
Replaces every @(text) with its translation.
TRANSLATE(text)| Parameter | Type | Description |
|---|---|---|
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.
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.
UNAUTHORIZED(...roles)| Parameter | Type | Description |
|---|---|---|
...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.
window.user = { roles: ['editor'] };
console.log(UNAUTHORIZED('editor')); // false
console.log(UNAUTHORIZED('admin')); // true
method
UNWATCH(path, [fn])
Removes a watcher.
UNWATCH(path, [fn])| Parameter | Type | Description |
|---|---|---|
path |
String |
The watched path. |
fn? |
Function |
The function given to WATCH(). |
Without a function, all watchers of the path are removed.
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.
UPD(path, [delay], [reset])| Parameter | Type | Description |
|---|---|---|
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.
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().
UPDATE(path, [delay], [reset])console.log(UPDATE === UPD); // true
method
UPLOAD(url, data, [callback], [delay], [progress])
Uploads data to a server.
UPLOAD(url, data, [callback], [delay], [progress])| Parameter | Type | Description |
|---|---|---|
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.
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.
VALID(path, [flags])| Parameter | Type | Description |
|---|---|---|
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.
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.
VBIND(html)| Parameter | Type | Description |
|---|---|---|
html |
String |
The HTML with bindings. |
Returns VBinder The virtual binder.
The object is described in Virtual binder, and the topic in Virtual bindings.
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.
VBINDARRAY(html, element)| Parameter | Type | Description |
|---|---|---|
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.
<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.
VERSION(...items)| Parameter | Type | Description |
|---|---|---|
...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.
<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.
VISIBLE(element, [threshold], [mode])| Parameter | Type | Description |
|---|---|---|
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.
<div id="box">Box</div>
<script>
console.log(VISIBLE($('#box'))); // true
</script>
property
W
A short name of window.
Wconsole.log(W === window); // true
method
WAIT(condition, callback, [interval], [timeout])
Waits until a condition is met.
WAIT(condition, callback, [interval], [timeout])| Parameter | Type | Description |
|---|---|---|
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('app.ready', function() {
console.log(GET('app.ready')); // true
}, 50);
setTimeout(() => SET('app.ready', true), 100);
WAIT(() => false, function(err) {
console.log(err.message); // Timeout.
}, 50, 200);
method
WAPI([name], [data], [callback], [timeout])
Calls an API over the WebSocket connection.
WAPI([name], [data], [callback], [timeout])| Parameter | Type | Description |
|---|---|---|
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.
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().
WAPI_INIT(options)| Parameter | Type | Description |
|---|---|---|
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).
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.
WARN(...args)| Parameter | Type | Description |
|---|---|---|
...args |
Object |
The values to write. |
WARN('Disk is full');
console.log(typeof(WARN)); // function
method
WATCH(path, fn, [init])
Calls a function when the value on a path changes.
WATCH(path, fn, [init])| Parameter | Type | Description |
|---|---|---|
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.
WATCH('user.name', function(path, value, type) {
console.log(path, value, type); // user.name Peter 1
});
SET('user.name', 'Peter');
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.
WATCHONCE(path, fn)| Parameter | Type | Description |
|---|---|---|
path |
String |
The path to watch. |
fn |
Function |
function(path, value, type). |
WATCHONCE('count', function(path, value) {
console.log(value); // 1
});
SET('count', 1);
SET('count', 2);
property
WH
The height of the window in pixels.
WHconsole.log(typeof(WH)); // number
method
WIDTH([element])
Returns the display size of the window or an element.
WIDTH([element])| Parameter | Type | Description |
|---|---|---|
element? |
jQuery |
The element. Default: window |
Returns String xs, sm, md or lg.
The limits are in DEF.devices.
<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.
WORKFLOW(declaration, [tasks], [callback])| Parameter | Type | Description |
|---|---|---|
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:
| Member | Description |
|---|---|
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, prev | The value, the current step and the previous step |
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.
WWconsole.log(typeof(WW)); // number