Global functions
The functions and variables that the library adds to the window object.
On this page
The library adds these functions and variables to window, so they are available everywhere in your code. Start with Paths and Data binding to see how they work together.
API
method
ADAPT(path, id, text)
Prepares a piece of HTML for a specific path and identifier.
ADAPT(path, id, text)| Parameter | Type | Description |
|---|---|---|
path |
String |
The value for ~PATH~ and CLASS. Use null to skip these replacements. |
id |
String |
The value for ~ID~. Use null to skip this replacement. |
text |
String |
The text to prepare. |
Returns String The prepared text.
The method translates @(text) markup, applies --name-- variables and replaces ~CDN~ with DEF.cdn. When path is set, ~PATH~ and CLASS become the path, <ui-plugin> elements without a path attribute receive it, and the first PLUGIN(function( becomes PLUGIN('path', function(. When id is set, ~ID~ becomes the identifier. A text that is empty or is not a string is returned unchanged.
var html = '<div class="CLASS" data-id="~ID~">~PATH~</div>';
console.log(ADAPT('users', 'u1', html)); // <div class="users" data-id="u1">users</div>
method
AJAX(url, [data], callback, [onprogress], [scope], [id])
Sends an HTTP request and delivers the response to a function or a path.
AJAX(url, [data], callback, [onprogress], [scope], [id])| Parameter | Type | Description |
|---|---|---|
url |
String |
The method, the address and optional keywords, for example POST /api/users/ ERROR. |
data? |
Object |
The request body: an object sent as JSON, a string sent as form data, or FormData. |
callback |
Function|String |
A function that receives the response, or a path that receives it. |
onprogress? |
Function|String |
A function or a path that receives the upload percentage. |
scope? |
Object |
The object in which a callback path is resolved. Default: window |
id? |
String |
The key used by SYNC and by the cache. Default: url |
The url starts with the HTTP method, followed by the address and optional keywords separated by spaces:
| Keyword | Meaning |
|---|---|
ERROR | Passes the response through ERROR(). If it holds an error, the ERROR event is emitted and callback does not run. An error status without a response body emits the ERROR event with the status code. |
SYNC | Queues requests with the same id, so that they run one after another. |
<1 minute> | Caches the response for the given time with CACHE(), unless it is an error. While the request is pending, other calls with the same id wait for its response, so only one request is sent. |
#name | Loads the code list name first. See CL(). |
@flag | Emits the flag when the request is sent. See Flags and path modifiers. |
An object in data is sent as JSON, a string is sent as it is with the content type application/x-www-form-urlencoded, and FormData is sent as a form.
A status code of 400 or higher counts as an error. A request that cannot reach the server, is aborted or runs out of time has the status code 0, and callback receives an empty response. A response with a JSON content type is parsed with PARSE(). Every request adds the headers from DEF.headers. When DEF.language is set, it is added to the query string. When DEF.version is set, it is added to the query string of .html addresses.
The request and response events let you inspect or change each call. Once the request is sent, options.xhr in the request event holds its XMLHttpRequest, so options.xhr.abort() stops it. UPLOAD() is the same function under another name.
AJAX('GET /api/users/', function(response) {
console.log(response.length); // 2
});
AJAX('POST /api/orders/', { amount: 10 }, 'orders.last');
WATCH('orders.last', function(value) {
console.log(value.id); // 100
});
AJAX('POST /api/login/', 'name=Ann&remember=1', function(response) {
console.log(response.ok); // true
});
var request;
ON('request', options => request = options);
ON('ERROR', status => console.log('failed', status)); // failed 0
AJAX('GET /api/report/ ERROR', NOOP);
request.xhr.abort();
method
API(url, name, [data], callback, [scope])
Calls a Total.js API endpoint on a specific address.
API(url, name, [data], callback, [scope])| Parameter | Type | Description |
|---|---|---|
url |
String |
The address of the endpoint. |
name |
String |
The name of the operation, optionally followed by keywords. |
data? |
Object |
The data of the operation. |
callback |
Function|String |
A function or a path that receives the response. |
scope? |
Object |
The object in which a callback path is resolved. Default: window |
API('/admin/api/', 'users_read', { id: 5 }, function(response) {
console.log(response.name); // Peter
});
method
APPEARANCE(options)
Sets the colour scheme of the page through CSS variables and body classes.
APPEARANCE(options)| Parameter | Type | Description |
|---|---|---|
options |
Object |
The switches and the CSS variables. |
Every key becomes a CSS variable on :root, except the four switches below. The color key also updates DEF.color and adds the variable --rgb with the red, green and blue values of a hexadecimal colour with three or six digits.
| Key | Meaning |
|---|---|
dark or darkmode | Toggles the class ui-dark on the body. |
large or largemode | Toggles the class ui-large on the body. |
The class prefix comes from DEF.prefixcsslibrary.
APPEARANCE({ dark: true, color: '#4285F4' });
console.log($('#cssappearance').html()); // :root{--color:#4285F4;--rgb:66,133,244}
console.log($('body').hclass('ui-dark')); // true
APPEARANCE({ color: '#abc' });
console.log($('#cssappearance').html()); // :root{--color:#abc;--rgb:170,187,204}
method
ASETTER(name, [a], [b], [c], [d])
Creates a function that calls a component method later.
ASETTER(name, [a], [b], [c], [d])| Parameter | Type | Description |
|---|---|---|
name |
String |
The selector and the method, in the same form as in SETTER(). |
a? |
Object |
The first argument. |
b? |
Object |
The second argument. |
c? |
Object |
The third argument. |
d? |
Object |
The fourth argument. |
Returns Function A function without arguments.
Each call of the returned function runs SETTER() with the arguments given here.
<ui-component name="counter"></ui-component>
<script>
COMPONENT('counter', function(self) {
self.add = function(value) {
console.log('added', value); // added 5
};
});
ON('ready', function() {
var add = ASETTER('counter/add', 5);
add();
});
</script>
method
ATTRD(element, [name])
Reads a data-* attribute from an element or from its closest parent that has it.
ATTRD(element, [name])| Parameter | Type | Description |
|---|---|---|
element |
jQuery|Event|Element|Object |
The starting point. |
name? |
String |
The attribute name without the data- prefix. Default: id |
Returns String The value of the attribute.
The element can be a jQuery object, a jQuery event (its currentTarget is used) or a DOM element. For a plain object, the method returns the property name. Any other value is returned as it is.
<div data-id="15" data-type="user"><button id="save">Save</button></div>
<script>
var button = $('#save');
console.log(ATTRD(button)); // 15
console.log(ATTRD(button, 'type')); // user
console.log(ATTRD({ id: 20 })); // 20
</script>
method
BLOCKED(key, timeout, [callback])
Limits how often an operation can run.
BLOCKED(key, timeout, [callback])| Parameter | Type | Description |
|---|---|---|
key |
String |
The name of the operation. |
timeout |
Number|String |
The time in milliseconds, or a text such as 5 minutes. |
callback? |
Function |
A function that runs when the operation is not blocked. |
Returns Boolean true when the operation is blocked.
The first call blocks key for the given time and returns false. Further calls return true until the time passes. A block of 10 seconds or longer is kept in localStorage, so it survives a page reload.
ON('ready', function() {
console.log(BLOCKED('save', 1000)); // false
console.log(BLOCKED('save', 1000)); // true
});
method
CACHE(key, [value], [expire])
Reads or writes a value in the persistent cache.
CACHE(key, [value], [expire])| Parameter | Type | Description |
|---|---|---|
key |
String |
The key. |
value? |
Object |
The value to store. |
expire? |
String |
The lifetime of the value, or session. |
Returns Object The stored value when reading, otherwise nothing.
With expire, the method stores the value. Without it, the method returns the stored value, or null when the value is missing or has expired. The value session keeps the data in memory until the page is closed. Any other value is a time such as 10 minutes, 2 hours, 1 day, 1 week, 1 month or 1 year, and the data is saved through DEF.onstoragesave.
The cache is loaded when the library starts, so use it from the ready event onward.
ON('ready', function() {
CACHE('filter', { page: 2 }, '1 day');
console.log(CACHE('filter')); // {"page":2}
console.log(CACHE('missing')); // null
});
method
CACHEPATH(path, expire, [def])
Keeps the value of a path in the cache between visits.
CACHEPATH(path, expire, [def])| Parameter | Type | Description |
|---|---|---|
path |
String |
The path. |
expire |
String |
The lifetime of the saved value, for example 1 day. |
def? |
Object|Function |
The value used when nothing is saved. A function is called to get it. |
The method saves every change of the path with CACHE() for the time in expire. When the path is empty, the saved value is written to it, and when nothing is saved, def is written. A path that already holds a value keeps it.
Called before the library has loaded the cache, the method waits for it and then restores the value. Plugins have the same method with a relative path: plugin.cachepath().
CACHEPATH('filter.q', '1 day', 'all');
console.log(GET('filter.q')); // all
SET('filter.q', 'lamp');
// After a reload of the page, GET('filter.q') returns lamp
method
CL(name, [callback])
Loads code lists registered with CLINIT().
CL(name, [callback])| Parameter | Type | Description |
|---|---|---|
name |
String |
One name, or several names separated by commas. |
callback? |
Function |
A function that runs when the lists are loaded. |
A code list is shared data, such as a list of countries, stored in DEF.cl. A list is loaded once. The callback runs when all the lists are available. A name that is not registered yet is checked again every 500 milliseconds until it appears.
CLINIT('countries', function(next) {
next([{ id: 'SK', name: 'Slovakia' }]);
});
ON('ready', function() {
CL('countries', function() {
console.log(DEF.cl.countries.length); // 1
});
});
method
clearTimeout2(name)
Cancels a timer created with setTimeout2().
clearTimeout2(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the timer. |
Returns Boolean true when the timer exists.
setTimeout2('search', NOOP, 1000);
console.log(clearTimeout2('search')); // true
console.log(clearTimeout2('unknown')); // false
method
CLINIT(name, source, [init])
Registers the source of a code list.
CLINIT(name, source, [init])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the code list. |
source |
Function|String |
A function, a request or an operation. |
init? |
Boolean |
Loads the list immediately. Default: false |
When source is a function, it receives next(value, [extend]). Pass the list to next(). With extend set to true, value is an object whose keys are stored as separate code lists.
When source is a string, a value that starts with an HTTP method is loaded with AJAX(). Any other value is an operation for TAPI().
CLINIT('all', function(next) {
next({ colors: ['red'], sizes: ['XL'] }, true);
}, true);
ON('ready', function() {
setTimeout(function() {
console.log(DEF.cl.colors, DEF.cl.sizes); // ["red"] ["XL"]
}, 100);
});
method
CLONE(value, [raw])
Creates a deep copy of a value.
CLONE(value, [raw])| Parameter | Type | Description |
|---|---|---|
value |
Object|String |
The value to copy, or a path. |
raw? |
Boolean |
Treats a string as a plain value. Default: false |
Returns Object The copy.
A string is treated as a path to an object or an array, and the value found there is copied. With raw set to true, a string is returned as it is. Objects are copied through JSON, and dates inside them stay dates.
var a = { user: { name: 'Peter' } };
var b = CLONE(a);
b.user.name = 'Lucia';
console.log(a.user.name); // Peter
SET('form', { name: 'Peter' });
var copy = CLONE('form');
console.log(copy); // {"name":"Peter"}
method
CLRELOAD(name, [callback])
Loads code lists again from their sources.
CLRELOAD(name, [callback])| Parameter | Type | Description |
|---|---|---|
name |
String |
One name, or several names separated by commas. |
callback? |
Function |
A function that runs when the lists are reloaded. |
Only lists that are already loaded are reloaded. Other names are skipped.
var counter = 0;
CLINIT('stats', function(next) {
next([++counter]);
});
ON('ready', function() {
CL('stats', function() {
CLRELOAD('stats', function() {
console.log(DEF.cl.stats); // [2]
});
});
});
method
CMD(name, [a], [b], [c], [d])
Runs a command on every component that registers it.
CMD(name, [a], [b], [c], [d])| Parameter | Type | Description |
|---|---|---|
name |
String |
The command, optionally followed by flags. |
a? |
Object |
The first argument. |
b? |
Object |
The second argument. |
c? |
Object |
The third argument. |
d? |
Object |
The fourth argument. |
Components register commands with command(). Flags can follow the name after a space, for example CMD('refresh @saved'): they are emitted first, as with SET(). To run a command only in a part of the page, use $(selector).CMD() or plugin.cmd().
<ui-component name="list"></ui-component>
<ui-component name="list"></ui-component>
<script>
var count = 0;
COMPONENT('list', function(self) {
self.command('clear', value => count += value);
});
ON('ready', function() {
CMD('clear', 1);
console.log(count); // 2
});
</script>
method
COMPONENT(name, [config], callback, [dependencies], [css])
Registers a component declaration.
COMPONENT(name, [config], callback, [dependencies], [css])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the component. |
config? |
String |
The default configuration in the form key:value;key:value. |
callback |
Function |
The declaration: function(self, config, cls). |
dependencies? |
String|Array |
Addresses to import first, separated by commas. An array can also contain functions that receive next. |
css? |
String |
The styles of the component. |
The callback runs once for every instance, and receives the instance, its configuration and its CSS class. In the css argument, the word CLASS becomes ui- followed by the component name. See Creating components and the Component object.
<ui-component name="hello"></ui-component>
<script>
COMPONENT('hello', 'name:World', function(self, config, cls) {
self.make = function() {
self.element.aclass(cls).html('Hello ' + config.name);
console.log(self.element.html()); // Hello World
};
});
</script>
method
COMPONENTS(path)
Returns the components bound to a path.
COMPONENTS(path)| Parameter | Type | Description |
|---|---|---|
path |
String |
The path, optionally with flags. |
Returns Array The matching component instances.
The path includes everything below it, so form also returns a component bound to form.name. Flags in the path narrow the result: @visible, @hidden, @touched, @modified, @required, @invalid, @valid, @disabled and @enabled.
<ui-component name="field" path="form.name" config="required:true"></ui-component>
<ui-component name="field" path="form.note"></ui-component>
<script>
COMPONENT('field', function(self) {
self.setter = NOOP;
});
ON('ready', function() {
console.log(COMPONENTS('form').length); // 2
console.log(COMPONENTS('form @required').length); // 1
});
</script>
method
CONFIG(selector, config)
Changes the configuration of existing and future components.
CONFIG(selector, config)| Parameter | Type | Description |
|---|---|---|
selector |
String|Function |
The components to configure. |
config |
String|Object |
The configuration, as an object or in the form key:value;key:value. |
The selector can be:
| Selector | Matches |
|---|---|
name | Components with this name. |
#id | The component with this identifier. |
.path | Components whose path contains path. |
* | All components. |
a, b | Several selectors separated by commas. |
function(instance) | Components for which the function returns true. |
<ui-component name="box"></ui-component>
<script>
COMPONENT('box', function(self) {});
ON('ready', function() {
CONFIG('box', 'color:red;size:10');
console.log(FIND('box').config.size); // 10
});
</script>
property
COOKIES
Reads and writes browser cookies.
COOKIESReturns Object The object with the methods.
The object has three methods:
| Method | Description |
|---|---|
COOKIES.get(name) | Returns the value, or an empty string. |
COOKIES.set(name, value, [expire], [samesite]) | Writes a cookie for the path /. expire is a number of days, a Date or a text such as 1 day. Without expire, the cookie is kept until the browser is closed. samesite is for example lax. |
COOKIES.rem(name) | Removes the cookie. |
COOKIES.set('theme', 'dark', '1 month', 'lax');
console.log(COOKIES.get('theme')); // dark
COOKIES.set('token', 'a=1', 7);
console.log(COOKIES.get('token')); // a=1
method
COPY(source, target)
Copies the properties of one object to another.
COPY(source, target)| Parameter | Type | Description |
|---|---|---|
source |
Object |
The object to read from. |
target |
Object |
The object to write to. |
Returns Object The target object.
Nested objects are cloned, so later changes in source do not affect target.
var target = { a: 1 };
COPY({ b: { c: 2 } }, target);
console.log(target); // {"a":1,"b":{"c":2}}
method
CSS(value, [id], [selector])
Another name for STYLE().
CSS(value, [id], [selector])| Parameter | Type | Description |
|---|---|---|
value |
String|Array |
The CSS. |
id? |
String |
The identifier of the style element. |
selector? |
String |
A selector that prefixes every rule. |
See STYLE(). Setting window.jc_globals = { CSS: false } ahead of the library script leaves this global undefined.
property
DAYS
The English names of the days of the week, starting with Sunday.
DAYSReturns Array Seven strings.
console.log(DAYS[1]); // Monday
property
DEF
The default settings of the library.
DEFReturns Object The settings.
Described on its own page: DEF.
method
DECRYPT(text, [key], [type])
Reads a value written by ENCRYPT().
DECRYPT(text, [key], [type])| Parameter | Type | Description |
|---|---|---|
text |
String |
The text from ENCRYPT(). |
key? |
String |
The key. |
type? |
String |
The prefix of the text. |
Returns Object The value, or undefined.
The key and the type must be the ones given to ENCRYPT(). The method returns undefined when the checksum does not match them, which is the case for a changed text. A value that starts with [, { or " is parsed as JSON.
var text = ENCRYPT({ id: 5 }, 'secret', 'U');
console.log(text.charAt(0)); // U
console.log(DECRYPT(text, 'secret', 'U')); // {"id":5}
console.log(DECRYPT(text, 'secret')); // undefined
method
DIFFDOM(element, selector, html, [attribute])
Updates the children of an element so that they match new HTML.
DIFFDOM(element, selector, html, [attribute])| Parameter | Type | Description |
|---|---|---|
element |
jQuery |
The parent element. |
selector |
String |
A selector of the compared children. |
html |
String |
The new content. |
attribute? |
String |
The attribute used for the comparison. |
Returns Object The number of added, kept and removed elements: { add, upd, rem }.
Children that have not changed stay in the DOM, so they keep their state. Children are compared by their whole HTML, or by the value of attribute when it is set.
<ul id="list"><li>A</li><li>B</li></ul>
<script>
var list = $('#list');
var result = DIFFDOM(list, 'li', '<li>A</li><li>C</li>');
console.log(result); // {"add":1,"upd":1,"rem":1}
console.log(list.html()); // <li>A</li><li>C</li>
</script>
method
EMIT(name, [a], [b], [c], [d])
Emits an event.
EMIT(name, [a], [b], [c], [d])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the event. |
a? |
Object |
The first argument. |
b? |
Object |
The second argument. |
c? |
Object |
The third argument. |
d? |
Object |
The fourth argument. |
Handlers registered with ON(), and handlers registered on components and plugins, receive the arguments. Flags can follow the name, for example refresh @loading. The events of the library are listed in Events.
ON('saved', function(id, name) {
console.log(id, name); // 5 Peter
});
EMIT('saved', 5, 'Peter');
property
EMPTYARRAY
A frozen empty array.
EMPTYARRAYReturns Array An array that cannot be changed.
console.log(Object.isFrozen(EMPTYARRAY)); // true
property
EMPTYOBJECT
A frozen empty object.
EMPTYOBJECTReturns Object An object that cannot be changed.
console.log(Object.isFrozen(EMPTYOBJECT)); // true
method
ENCRYPT(value, [key], [type])
Encodes a value as text with a checksum.
ENCRYPT(value, [key], [type])| Parameter | Type | Description |
|---|---|---|
value |
String|Object |
The value. |
key? |
String |
The key of the checksum. |
type? |
String |
A prefix written at the beginning of the text. |
Returns String The encoded text.
An object or an array is serialized with STRINGIFY() first. The result has the type as a prefix, the value in hexadecimal digits, the letter x and a checksum made with HASH() from the value, the key and the type.
The value can be read back by anyone, so do not use the method to hide data: the key only lets DECRYPT() find out whether the text was changed.
var text = ENCRYPT('hello', 'secret');
console.log(text); // 68656c6c6fxds46dr
console.log(DECRYPT(text, 'secret')); // hello
console.log(DECRYPT(text, 'other')); // undefined
method
ENV(name, [value])
Reads or writes environment variables.
ENV(name, [value])| Parameter | Type | Description |
|---|---|---|
name |
String|Object |
The name, or an object with names and values. |
value? |
Object |
The value to write. |
Returns Object The value of the variable.
ENV('api', '/api/v1/');
console.log(ENV('api')); // /api/v1/
console.log('[api]users/'.env()); // /api/v1/users/
method
ENVIRONMENT(name, [version], [language], [env])
Sets the storage key, version, language and environment variables of the app.
ENVIRONMENT(name, [version], [language], [env])| Parameter | Type | Description |
|---|---|---|
name |
String |
The key used in localStorage. |
version? |
String |
The version of the app. |
language? |
String |
The language of the app. |
env? |
Object |
Environment variables. |
The method assigns DEF.localstorage, DEF.version and DEF.language, and passes env to ENV(). Call it directly after the library script, so that the app reads its own storage.
ENVIRONMENT('myapp', '1.0', 'en', { title: 'My app' });
console.log(DEF.localstorage, DEF.version, DEF.language); // myapp 1.0 en
console.log(ENV('title')); // My app
method
ERROR(response, [success], [error])
Checks a response for errors and runs the matching handler.
ERROR(response, [success], [error])| Parameter | Type | Description |
|---|---|---|
response |
Object |
The response to check. |
success? |
Function|String |
Runs when there is no error. |
error? |
Function|String |
Runs when there is an error. |
Returns Boolean true when the response holds an error.
A response is an error when it is an Error object, has an error property, or is an array whose first item has one. An error emits the ERROR event.
success and error can be functions, or names for SEEX().
Call ERROR(success, [error]) without a response to create a function that you can pass as a callback.
console.log(ERROR({ id: 1 })); // false
console.log(ERROR([{ error: 'Invalid name' }])); // true
var callback = ERROR(function(response) {
console.log(response.id); // 1
});
callback({ id: 1 });
method
ERRORS(path, callback)
Returns the invalid components of a path or of an element.
ERRORS(path, callback)| Parameter | Type | Description |
|---|---|---|
path |
String|jQuery |
A path, or an element that contains the components. |
callback |
Function |
A function that receives an array of components. |
<ui-component name="field" path="form.name" config="required:true"></ui-component>
<script>
COMPONENT('field', function(self) {
self.validate = function(value) {
return !!value;
};
});
ON('ready', function() {
ERRORS('form', function(components) {
console.log(components.length); // 1
});
});
</script>
method
EXEC(name, [a], [b], [c], [d])
Calls a function by its name.
EXEC(name, [a], [b], [c], [d])| Parameter | Type | Description |
|---|---|---|
name |
String |
The target of the call. |
a? |
Object |
The first argument. |
b? |
Object |
The second argument. |
c? |
Object |
The third argument. |
d? |
Object |
The fourth argument. |
The form of name decides what is called:
| Name | Calls |
|---|---|
name | A global function. |
FUNC.name | A function found at a path. |
plugin/method | A method of a plugin. |
*/method | A method of the common plugin. |
-component/method | A component method, through SETTER(). |
#event | An event, through EMIT(). |
Add the flag @important to retry every 500 milliseconds until the function exists, for example EXEC('app/refresh @important'). EXE() is the same function under another name.
FUNC.sum = function(a, b) {
console.log(a + b); // 5
};
EXEC('FUNC.sum', 2, 3);
EXEC('app.start @important', 'now');
setTimeout(function() {
window.app = {};
app.start = function(value) {
console.log(value); // now
};
}, 100);
method
EXTENSION(name, [config], callback)
Extends a component or a plugin.
EXTENSION(name, [config], callback)| Parameter | Type | Description |
|---|---|---|
name |
String |
The component name, or @ followed by the plugin name. |
config? |
String|Object |
Configuration added to each instance. |
callback |
Function |
A function (instance, config, cls), where cls is the CSS class of the instance. this is the instance. |
The callback runs for every existing instance and for every new one, right after the declaration, always with the same arguments. For a plugin, write @ in front of its name.
<ui-component name="box"></ui-component>
<script>
COMPONENT('box', function(self) {});
EXTENSION('box', 'color:red', function(self, config) {
self.describe = function() {
return config.color;
};
});
ON('ready', function() {
console.log(FIND('box').describe()); // red
});
</script>
method
FIND(selector, [all])
Finds a component that is ready.
FIND(selector, [all])| Parameter | Type | Description |
|---|---|---|
selector |
String |
The name, the identifier or the path. |
all? |
Boolean |
Returns all the matches in an array. Default: false |
Returns Component|Array The first component, or an array when all is true.
The selector is a component name, #id for an identifier, or .path for a path.
<ui-component name="field" path="form.name"></ui-component>
<script>
COMPONENT('field', function(self) {});
ON('ready', function() {
console.log(FIND('field').name); // field
console.log(FIND('.form.name').path.path); // form.name
console.log(FIND('field', true).length); // 1
});
</script>
method
FLAGS(flags, [callback])
Emits flags and then runs a function.
FLAGS(flags, [callback])| Parameter | Type | Description |
|---|---|---|
flags |
String |
The flags, for example @loading @save. |
callback? |
Function |
A function that runs afterwards. |
Each flag emits the event @flag name, which you can capture with ON(). See Flags and path modifiers.
ON('@flag loading', function() {
console.log('flag captured'); // flag captured
});
FLAGS('@loading', function() {
console.log('done'); // done
});
method
FN(code)
Compiles an arrow function from a string.
FN(code)| Parameter | Type | Description |
|---|---|---|
code |
String |
The code of the function. |
Returns Function The compiled function.
The code can have up to four arguments. Code without an arrow becomes a function with the argument value. Compiled functions are cached.
console.log(FN('n => n * 2')(4)); // 8
console.log(FN('(a, b) => a + b')(1, 2)); // 3
console.log(FN('value + 1')(1)); // 2
method
FREE()
Removes components, bindings and plugins whose elements have left the DOM.
FREE()The library runs this cleanup every minute. Call it when you need the instances to be removed right away.
<ui-component name="box" path="form.name"></ui-component>
<script>
COMPONENT('box', function(self) {});
ON('ready', function() {
$('ui-component').remove();
FREE();
console.log(COMPONENTS('form').length); // 0
});
</script>
property
FUNC
An empty object for the functions of your app.
FUNCReturns Object The container.
Functions stored here can be called by path with EXEC().
FUNC.hello = function() {
return 'Hello';
};
console.log(FUNC.hello()); // Hello
method
GET(path, [noflags])
Reads the value of a path.
GET(path, [noflags])| Parameter | Type | Description |
|---|---|---|
path |
String |
The path, optionally with flags. |
noflags? |
Boolean |
Reads the value without applying the flags. Default: false |
Returns Object The value.
When the path contains flags, they are applied to the components of the path: GET('form @reset') returns the value and resets their state. See Paths.
SET('user.name', 'Peter');
console.log(GET('user.name')); // Peter
console.log(GET('user')); // {"name":"Peter"}
method
GUID([length])
Generates a random identifier.
GUID([length])| Parameter | Type | Description |
|---|---|---|
length? |
Number |
The length of the identifier. |
Returns String The identifier.
Without length, the result has the 36-character form of a UUID. With length, it is a string of lowercase letters and digits.
console.log(GUID().length); // 36
console.log(GUID(10).length); // 10
method
HASH(value)
Creates a numeric hash of a value.
HASH(value)| Parameter | Type | Description |
|---|---|---|
value |
String|Number|Boolean|Object|Date |
The value. |
Returns Number The hash.
A number is returned as it is, true gives 1, a date gives its time in milliseconds, and an empty value gives 0. Objects are serialized first.
console.log(HASH('hello')); // 99162322
method
IMPORT(url, [target], [callback], [prepare])
Loads a script, a stylesheet or a piece of HTML.
IMPORT(url, [target], [callback], [prepare])| Parameter | Type | Description |
|---|---|---|
url |
String |
The address and optional keywords. |
target? |
String|jQuery|Element |
The element that receives HTML content. Default: body |
callback? |
Function |
A function that runs when the content is loaded. |
prepare? |
Function |
A function that receives the HTML and returns the text to insert. |
Addresses ending with .js or .css are added to the page head. Any other address is downloaded and inserted into target. Keywords can be combined with the address:
| Keyword | Meaning |
|---|---|
<name> | Skips the import when the global variable name exists. |
.js, .css, .html | Sets the type of the content when the address does not show it. |
@singleton | Imports the address only once. |
@prepend | Inserts the content at the beginning of target. |
When a script or a stylesheet cannot be loaded, the library writes a warning to the console and callback still runs.
See Importing content.
<div id="menu"></div>
<script>
IMPORT('/parts/menu.html', '#menu', function() {
console.log($('#menu').html()); // <b>Menu</b>
});
</script>
IMPORT('<jQuery> /js/jquery.min.js', function() {
console.log('jQuery is available'); // jQuery is available
});
method
INC(path, [value])
Increases the number stored in a path.
INC(path, [value])| Parameter | Type | Description |
|---|---|---|
path |
String |
The path. |
value? |
Number |
The amount to add. Default: 1 |
An empty path starts at 0. A string is converted to a number. Use a negative value to decrease the number.
SET('stats.visits', 10);
INC('stats.visits');
INC('stats.visits', 5);
console.log(GET('stats.visits')); // 16
method
inDOM(element)
Checks whether an element is attached to the document body.
inDOM(element)| Parameter | Type | Description |
|---|---|---|
element |
Element |
A DOM element. |
Returns Boolean true when the element is attached, otherwise nothing.
console.log(inDOM(document.body)); // true
console.log(!!inDOM(document.createElement('div'))); // false
property
isIE
Tells whether the browser is Internet Explorer.
isIEReturns Boolean The result of the detection.
property
isMOBILE
Tells whether the user agent belongs to a mobile device.
isMOBILEReturns Boolean The result of the detection.
property
isPRIVATEMODE
Tells whether localStorage is unavailable, as in some private windows. The value is set while the library starts, so read it from the ready event onward.
isPRIVATEMODEReturns Boolean The result of the detection.
property
isROBOT
Tells whether the user agent belongs to a search engine or a crawler.
isROBOTReturns Boolean The result of the detection.
property
isSTANDALONE
Tells whether the page runs as an installed web app.
isSTANDALONEReturns Boolean The result of the detection.
property
isTOUCH
Tells whether the device supports touch input.
isTOUCHReturns Boolean The result of the detection.
property
jComponent
The main object of the library.
jComponentReturns Object The main object.
The same object as MAIN.
method
LOCALIZE(text)
Loads translations into the dictionary.
LOCALIZE(text)| Parameter | Type | Description |
|---|---|---|
text |
String |
The lines with translations. |
Each line has the form key : translation, and lines starting with // are skipped. The key is the hash of the original text, in base 36, with the prefix T. The translations are stored in DEF.dictionary and used by TRANSLATE(). See Localization.
var key = 'T' + HASH('Hello').toString(36);
LOCALIZE(key + ' : Hola');
console.log(TRANSLATE('@(Hello)')); // Hola
property
M
A short name of the main object.
MReturns Object The main object.
The same object as MAIN.
property
MAIN
The main object of the library.
MAINReturns Object The main object.
Described on its own page: MAIN.
property
MONTHS
The English names of the months, starting with January.
MONTHSReturns Array Twelve strings.
console.log(MONTHS[0]); // January
method
NEWUIBIND(element, [path], [config])
Creates a data binding on an element from code.
NEWUIBIND(element, [path], [config])| Parameter | Type | Description |
|---|---|---|
element |
jQuery|Element |
The element. |
path? |
String |
The path to observe. |
config? |
String |
The binding commands. |
The binding works like the ui-bind element. Without path and config, the values are read from the attributes of the element.
<div id="name"></div>
<script>
SET('user.name', 'Peter');
NEWUIBIND($('#name'), 'user.name', 'text:value');
setTimeout(function() {
console.log($('#name').html()); // Peter
}, 200);
</script>
method
NODEINDEXOF(element)
Returns the position of an element among its siblings.
NODEINDEXOF(element)| Parameter | Type | Description |
|---|---|---|
element |
jQuery|Element |
The element. |
Returns Number The zero-based position.
<ul><li id="a">A</li><li id="b">B</li></ul>
<script>
console.log(NODEINDEXOF($('#b'))); // 1
</script>
method
NODEINSERT(element, reference, [before])
Inserts an element next to another element.
NODEINSERT(element, reference, [before])| Parameter | Type | Description |
|---|---|---|
element |
jQuery|Element |
The element to insert. |
reference |
jQuery|Element |
The reference element. |
before? |
Boolean |
Inserts the element in front of the reference. Default: false |
<ul><li id="a">A</li><li id="b">B</li><li id="c">C</li></ul>
<script>
NODEINSERT($('#c'), $('#a'), true);
console.log($('ul').text()); // CAB
</script>
method
NODEMOVE(element, [up])
Moves an element one position among its siblings.
NODEMOVE(element, [up])| Parameter | Type | Description |
|---|---|---|
element |
jQuery|Element |
The element. |
up? |
Boolean |
Moves the element towards the start. Otherwise it moves towards the end. Default: false |
<ul><li id="a">A</li><li id="b">B</li><li id="c">C</li></ul>
<script>
NODEMOVE($('#b'), true);
console.log($('ul').text()); // BAC
</script>
method
NOOP()
A function that does nothing.
NOOP()Use it as a default callback.
var callback = NOOP;
console.log(typeof(callback)); // function
method
NOTFOCUSED()
Checks whether the page is in the background.
NOTFOCUSED()Returns Boolean true when the document is hidden.
console.log(NOTFOCUSED()); // false
property
NOW
The current date, refreshed once a minute.
NOWReturns Date The date.
Use it when a precision of one minute is enough. It avoids creating a new Date object for each use.
console.log(NOW instanceof Date); // true
method
NUL(path)
Sets a path to null.
NUL(path)| Parameter | Type | Description |
|---|---|---|
path |
String |
The path. |
NULL() is the same function under another name.
SET('user.name', 'Peter');
NUL('user.name');
console.log(GET('user.name')); // null
method
OFF(name, [callback])
Removes event handlers.
OFF(name, [callback])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the event. |
callback? |
Function |
The handler to remove. |
Without callback, all the handlers of the event are removed. Several events can be joined with +.
var count = 0;
var handler = function() {
count++;
};
ON('refresh', handler);
EMIT('refresh');
OFF('refresh', handler);
EMIT('refresh');
console.log(count); // 1
method
ON(name, callback, [init])
Registers an event handler.
ON(name, callback, [init])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the event. |
callback |
Function |
The handler. It receives the arguments of the event. |
init? |
Boolean |
Also calls the handler once, without arguments. Default: false |
Several events can be joined with +, for example saved + removed. A handler for ready or init runs immediately when the library has started. The events of the library are listed in Events.
var count = 0;
ON('saved + removed', function() {
count++;
});
EMIT('saved');
EMIT('removed');
console.log(count); // 2
method
PARSE(value)
Parses JSON and converts date strings to Date objects.
PARSE(value)| Parameter | Type | Description |
|---|---|---|
value |
String|Object |
The JSON, a selector or an object. |
Returns Object The parsed value, or null.
A value starting with # or . is a selector: the JSON is read from the content of that element. An object is returned as it is. Invalid JSON returns null.
var data = PARSE('{"created":"2024-05-01T10:00:00.000Z"}');
console.log(data.created instanceof Date); // true
console.log(PARSE('invalid')); // null
method
PIPE(name, [data], callback, [scope])
Calls an operation on the address from DEF.pipe.
PIPE(name, [data], callback, [scope])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the operation, optionally followed by keywords. |
data? |
Object |
The data of the operation. |
callback |
Function|String |
A function or a path that receives the response. |
scope? |
Object |
The object in which a callback path is resolved. Default: window |
DEF.pipe = '/pipe/';
PIPE('orders_list', function(response) {
console.log(response.length); // 1
});
method
PLUGIN(name, [config], callback, [dependencies])
Registers a plugin declaration.
PLUGIN(name, [config], callback, [dependencies])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the plugin. |
config? |
String |
The default configuration in the form key:value;key:value. |
callback |
Function |
The declaration: function(self, config). |
dependencies? |
String|Array |
Addresses to import first. |
<ui-plugin path="users"></ui-plugin>
<script>
PLUGIN('users', function(self) {
self.hello = function(name) {
console.log('Hello ' + name); // Hello Peter
};
});
ON('ready', function() {
EXEC('users/hello', 'Peter');
});
</script>
property
PLUGINS
The running plugin instances, by name.
PLUGINSReturns Object The plugin instances.
<ui-plugin path="users"></ui-plugin>
<script>
PLUGIN('users', function(self) {});
ON('ready', function() {
console.log(Object.keys(PLUGINS)); // ["users"]
});
</script>
property
PREF
Persistent user preferences.
PREFReturns Object The preferences.
Described on its own page: PREF.
method
PUSH(path, value)
Adds an item to the array stored in a path and notifies the path.
PUSH(path, value)| Parameter | Type | Description |
|---|---|---|
path |
String |
The path of an existing array. |
value |
Object |
The item. |
Write ^ in front of the path to add the item at the beginning of the array.
SET('tags', ['b']);
PUSH('tags', 'c');
PUSH('^tags', 'a');
console.log(GET('tags')); // ["a","b","c"]
method
QUERIFY([url], data)
Adds data to an address as a query string.
QUERIFY([url], data)| Parameter | Type | Description |
|---|---|---|
url? |
String |
The address. |
data |
Object |
The values. |
Returns String The address with the query string.
Empty values are skipped, dates are converted to ISO strings and arrays are joined with commas. The url can start with an HTTP method.
console.log(QUERIFY('/users/', { page: 2, q: 'a b' })); // /users/?page=2&q=a%20b
console.log(QUERIFY('GET /users/', { page: 2 })); // GET /users/?page=2
console.log(QUERIFY({ page: 2 })); // ?page=2
property
REPO
An empty object for the shared data of your app.
REPOReturns Object The container.
REPO.title = 'My app';
console.log(REPO.title); // My app
method
RESET(path)
Resets the state of the components bound to a path.
RESET(path)| Parameter | Type | Description |
|---|---|---|
path |
String |
The path. |
The touched and modified states return to their defaults. The value of the path does not change.
<ui-component name="field" path="form.name"></ui-component>
<script>
COMPONENT('field', function(self) {});
ON('ready', function() {
SET('form.name @change', 'Peter');
console.log(FIND('field').config.modified); // 1
RESET('form');
console.log(FIND('field').config.modified); // 0
console.log(GET('form.name')); // Peter
});
</script>
method
SCROLLBAR(element, [options])
Adds a custom scrollbar to an element.
SCROLLBAR(element, [options])| Parameter | Type | Description |
|---|---|---|
element |
jQuery |
The element. |
options? |
Object |
The options. |
Returns Object The scrollbar.
Options:
| Option | Type | Description |
|---|---|---|
native | Boolean | Keeps the scrollbar of the browser and only sets the overflow. |
orientation | String | x or y. By default, both directions are active. |
visibleX, visibleY | Boolean | Keeps the track visible when there is nothing to scroll. |
wrap | Boolean | false uses the existing content as the scroll area. |
controls | jQuery | The element that receives the scrollbar tracks. |
shadow | Boolean | Adds shadows on the scrollable edges. |
padding | Number | The distance of the tracks from the edge. Default 5. |
minsize | Number | The minimum size of the bar. Default 50. |
thickness | Number | The thickness used when CSS does not define it. Default 10. |
margin, marginX, marginY | Number | Adjust the size of the scroll area. |
offsetX, offsetY | Number | Adjust the measured size of the element. |
floating | Boolean | false reserves space for the bars. |
parent | String|jQuery | The element whose size is used. |
interval | Number | The time between size checks, in milliseconds. Default 54321. |
autoresize | Boolean | false stops measuring the element again when the window is resized. Default true. |
onscroll, onidle, onresize | Function | Handlers that receive the scrollbar. |
The returned object provides:
| Member | Description |
|---|---|
area | The scrolling element. |
body | The element with the content. |
element | The original element. |
resize() | Measures the element again. |
scrollTop([value]) | Reads or sets the vertical position. A string such as '+20' moves relative to the current position. |
scrollLeft([value]) | Reads or sets the horizontal position, with the same rules. |
scrollBottom(offset) | Scrolls to the bottom, minus offset. |
scrollRight(offset) | Scrolls to the right edge, minus offset. |
scroll(x, y) | Scrolls to a position. |
sync(element, [direction]) | Synchronizes scrolling with another element. direction is x or y. |
destroy() | Stops the scrollbar. |
The scroll and scrollidle events report scrolling.
<div id="panel" style="width:200px;height:100px"><div style="height:600px">Content</div></div>
<script>
var scrollbar = SCROLLBAR($('#panel'));
scrollbar.area.css('overflow', 'auto');
scrollbar.resize(false, true);
scrollbar.scrollTop(30);
console.log(scrollbar.scrollTop()); // 30
scrollbar.scrollTop('+20');
console.log(scrollbar.scrollTop()); // 50
</script>
method
SCROLLBARWIDTH()
Returns the width of the scrollbar of the browser.
SCROLLBARWIDTH()Returns Number The width in pixels.
console.log(typeof(SCROLLBARWIDTH())); // number
method
SEEX(name, [a], [b], [c], [d])
Calls a function or writes a value, depending on the name.
SEEX(name, [a], [b], [c], [d])| Parameter | Type | Description |
|---|---|---|
name |
String |
The target. |
a? |
Object |
The first argument. |
b? |
Object |
The second argument. |
c? |
Object |
The third argument. |
d? |
Object |
The fourth argument. |
The form plugin/method calls a plugin method, and the name of a global function calls that function. Any other name is a path, and a is written to it with SET().
SEEX('form.name', 'Peter');
console.log(GET('form.name')); // Peter
window.notify = function(text) {
console.log(text); // Saved
};
SEEX('notify', 'Saved');
method
SET(path, value)
Writes a value to a path and notifies everything that observes it.
SET(path, value)| Parameter | Type | Description |
|---|---|---|
path |
String |
The path, optionally with flags. |
value |
Object |
The value, or a function (current) that returns it. |
Missing objects along the path are created. Flags are part of the path, for example form.name @change. The form path[] appends the value to an array. A function as value receives the current value, and its result is written. See Paths and Flags and path modifiers.
SET('user.name', 'Peter');
SET('user.tags[]', 'admin');
console.log(GET('user')); // {"name":"Peter","tags":["admin"]}
SET('cart.count', 1);
SET('cart.count', value => value + 1);
console.log(GET('cart.count')); // 2
method
SETTER(name, [a], [b], [c], [d])
Calls a method on the components that match a selector.
SETTER(name, [a], [b], [c], [d])| Parameter | Type | Description |
|---|---|---|
name |
String |
The selector and the method. |
a? |
Object |
The first argument. |
b? |
Object |
The second argument. |
c? |
Object |
The third argument. |
d? |
Object |
The fourth argument. |
The name has the form selector/method:
| Selector | Matches |
|---|---|
name | Components with this name. |
#id | The component with this identifier. |
* | All components that have the method. |
The flag @important retries every 500 milliseconds until a matching component with the method exists. A component declared as lazy is created by the first call, unless the name starts with !.
<ui-component name="counter"></ui-component>
<script>
COMPONENT('counter', function(self) {
self.add = function(value) {
console.log(value); // 5
};
});
ON('ready', function() {
SETTER('counter/add', 5);
});
</script>
method
setTimeout2(name, callback, timeout, [limit], [param])
Runs a function after a delay, restarting the delay on each call with the same name.
setTimeout2(name, callback, timeout, [limit], [param])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the timer. |
callback |
Function |
The function. |
timeout |
Number |
The delay in milliseconds. |
limit? |
Number |
The maximum number of calls in one waiting period. |
param? |
Object |
The argument of the function. |
Returns String The name of the timer. A call ignored by limit returns nothing.
With limit, the delay is restarted at most limit times. Further calls are ignored until the function runs, so it cannot be postponed forever.
var count = 0;
var run = function() {
count++;
console.log(count); // 1
};
setTimeout2('search', run, 50);
setTimeout2('search', run, 50);
setTimeout2('search', run, 50);
method
STRINGIFY(value, [compress], [fields], [encrypt])
Serializes a value to JSON.
STRINGIFY(value, [compress], [fields], [encrypt])| Parameter | Type | Description |
|---|---|---|
value |
Object |
The value. |
compress? |
Boolean |
Removes empty values. Default: false |
fields? |
Array|Object|Function |
The keys to keep. |
encrypt? |
Boolean|String |
true encodes the JSON with ENCRYPT(). A string does the same and is the key. |
Returns String The JSON.
With compress set to true, strings are trimmed, and empty strings, false and null are left out. The fields argument selects the keys: an array of allowed keys, an object where false excludes a key, or a function (key, value) that returns true for the keys to keep.
var data = { name: ' Peter ', note: '', age: 30 };
console.log(STRINGIFY(data, true)); // {"name":"Peter","age":30}
console.log(STRINGIFY(data, false, ['age'])); // {"age":30}
var text = STRINGIFY({ id: 5 }, false, null, 'secret');
console.log(DECRYPT(text, 'secret')); // {"id":5}
method
STYLE(value, [id], [selector])
Adds CSS to the page.
STYLE(value, [id], [selector])| Parameter | Type | Description |
|---|---|---|
value |
String|Array |
The CSS. |
id? |
String |
The identifier of the style element. |
selector? |
String |
A selector that prefixes every rule. |
An element with the same id is replaced. The element has the identifier css followed by id. With selector, every rule is prefixed with this selector.
STYLE('b { color: red }', 'theme', '.panel');
console.log($('#csstheme').html()); // .panel b{ color: red }
method
TAPI(name, [data], callback, [scope])
Calls a Total.js API operation on the address from DEF.api.
TAPI(name, [data], callback, [scope])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the operation, optionally followed by keywords. |
data? |
Object |
The data of the operation. |
callback |
Function|String |
A function or a path that receives the response. |
scope? |
Object |
The object in which a callback path is resolved. Default: window |
DEF.api = '/admin/api/';
TAPI('users_list', { page: 1 }, 'users.items');
WATCH('users.items', function(value) {
console.log(value.length); // 2
});
property
TEMP
An object for short-lived data.
TEMPReturns Object The container.
The library replaces it with an empty object every minute.
TEMP.result = 5;
console.log(TEMP.result); // 5
method
TOGGLE(path)
Inverts the boolean value of a path.
TOGGLE(path)| Parameter | Type | Description |
|---|---|---|
path |
String |
The path. |
SET('menu.open', false);
TOGGLE('menu.open');
console.log(GET('menu.open')); // true
property
Total
The main object of the library.
TotalReturns Object The main object.
The same object as MAIN.
method
TRANSLATE(text)
Replaces the @(text) markup with translations.
TRANSLATE(text)| Parameter | Type | Description |
|---|---|---|
text |
String |
The text with the markup. |
Returns String The translated text.
Text without a translation stays in its original language. Translations are loaded with LOCALIZE().
LOCALIZE('T' + HASH('Yes').toString(36) + ' : Ano');
console.log(TRANSLATE('@(Yes) / @(No)')); // Ano / No
method
UNAUTHORIZED(...permissions)
Checks the permissions of the signed-in user.
UNAUTHORIZED(...permissions)| Parameter | Type | Description |
|---|---|---|
permissions |
String |
One or more permissions. |
Returns Boolean true when access is denied.
The method reads the global variable user. A user with sa or su set has all the permissions. Otherwise, the permissions come from user.permissions or user.roles, as an array or an object. The result is true when the user has none of the given permissions, or when user does not exist.
window.user = { roles: ['editor'] };
console.log(UNAUTHORIZED('editor')); // false
console.log(UNAUTHORIZED('admin')); // true
method
UNWATCH(path, [callback])
Removes watchers from a path.
UNWATCH(path, [callback])| Parameter | Type | Description |
|---|---|---|
path |
String |
The path. Several paths can be joined with +. |
callback? |
Function |
The watcher to remove. |
Without callback, all the watchers of the path are removed.
var count = 0;
var watcher = function() {
count++;
};
WATCH('form.name', watcher);
SET('form.name', 'A');
UNWATCH('form.name', watcher);
SET('form.name', 'B');
console.log(count); // 1
method
UPD(path)
Notifies a path after its value was changed directly.
UPD(path)| Parameter | Type | Description |
|---|---|---|
path |
String |
The path, optionally with flags. |
UPDATE() is the same function under another name.
window.form = { name: 'A' };
WATCH('form.name', function(value) {
console.log(value); // B
});
form.name = 'B';
UPD('form.name');
method
VISIBLE(element, [threshold], [mode])
Checks the vertical position of an element relative to the viewport.
VISIBLE(element, [threshold], [mode])| Parameter | Type | Description |
|---|---|---|
element |
jQuery|Element |
The element. |
threshold? |
Number |
The number of pixels of the element that must be inside the viewport. Default: 0 |
mode? |
String |
visible, above or below. Default: visible |
Returns Boolean The result of the check.
The mode selects the check: visible tests whether the element is in the viewport, above whether it is above it, and below whether it is below it. A hidden element returns false.
<div id="top">Top</div>
<div style="height:5000px"></div>
<div id="far">Far</div>
<script>
console.log(VISIBLE($('#top'))); // true
console.log(VISIBLE($('#far'))); // false
console.log(VISIBLE($('#far'), 0, 'below')); // true
</script>
property
W
A short name of the window object.
WReturns Object The window object.
console.log(W === window); // true
method
WAIT(condition, callback)
Runs a function when a condition is met.
WAIT(condition, callback)| Parameter | Type | Description |
|---|---|---|
condition |
Function|String |
A function or a path. |
callback |
Function |
The function to run. |
The condition is checked immediately and then every 500 milliseconds. A function must return a truthy value. For a path, the wait ends when the path holds a truthy value.
WAIT('app.config', function() {
console.log(GET('app.config.name')); // Demo
});
setTimeout(function() {
SET('app.config', { name: 'Demo' });
}, 100);
method
WARN(...values)
Prints a warning to the browser console.
WARN(...values)| Parameter | Type | Description |
|---|---|---|
values |
Object |
The values to print. |
method
WATCH(path, callback, [init])
Observes changes of a path.
WATCH(path, callback, [init])| Parameter | Type | Description |
|---|---|---|
path |
String |
The path. |
callback |
Function |
A function that receives (value, flags, path): the watched value, the flags and the changed path. |
init? |
Boolean |
Also calls the watcher once after the registration. Default: false |
A watcher runs when its own path changes, when a parent path changes, and when a path nested below it changes. Several paths can be joined with +.
WATCH('user.name', function(value, flags, path) {
console.log(value, path); // Peter user.name
});
SET('user.name', 'Peter');
property
WH
The height of the window in pixels.
WHReturns Number The height.
The value is set while the library starts, and is refreshed when the window is resized.
ON('ready', function() {
console.log(typeof(WH)); // number
});
method
WIDTH([element])
Returns the name of the device size for the width of an element.
WIDTH([element])| Parameter | Type | Description |
|---|---|---|
element? |
jQuery |
The measured element. Default: window |
Returns String The name of the size.
The sizes xs, sm, md and lg are defined in DEF.devices.
<div id="box" style="width:800px"></div>
<script>
console.log(WIDTH($('#box'))); // sm
</script>
property
WW
The width of the window in pixels.
WWReturns Number The width.
The value is set while the library starts, and is refreshed when the window is resized.
ON('ready', function() {
console.log(typeof(WW)); // number
});