jComponent / 03. Globals
Updated: 11. October 2018
Author: Peter Širka

03. Globals

Professional Support Chat with contributors

This is very important part of the jComponent library because this part contains documentation for all global properties and methods defined in window scope.

Quick navigation:


Properties

Property: DAYS

Property contains names of days. Of course, you can localize it.

DAYS;
// returns {Array String}

console.log(DAYS[0]);
// Output: Sunday

Property: DEF

+v14.0.0 is alias for MAIN.defaults.

DEF;
// returns {Object}

DEF.fallbackcache = '5 minutes';

Property: EMPTYARRAY

readonly This property returns readonly empty Array.

EMPTYARRAY;
// returns {Array}

Property: EMPTYOBJECT

readonly This property returns readonly empty Object.

EMPTYOBJECT;
// returns {Object}

Property: FUNC

+v16 This property returns empty object for storing inline functions.

FUNC;
// returns {Object}

Property: isMOBILE

readonly It detects a mobile device.

isMOBILE;
// returns {Boolean}

Property: isPRIVATEMODE

Determines whether localStorage is disabled --> PRIVATEMODE = true.

PRIVATEMODE;
// returns {Boolean}

console.log(PRIVATEMODE);
// Output: false

Property: isROBOT

readonly It detects a robot/crawler.

isROBOT;
// returns {Boolean}

Property: isSTANDALONE

readonly It detects a standalone application.

isSTANDALONE;
// returns {Boolean}

Property: isTOUCH

readonly It detects a touch display.

isTOUCH;
// returns {Boolean}

Property: MONTHS

Property contains names of months. Of course, you can localize it.

MONTHS;
// returns {Array String}

console.log(MONTHS[0]);
// Output: January

Property: NOW

Property contains a current Date object. It's refreshed in 1 minute.

NOW;
// returns {Date}

Methods

Method: ADD()

+v16 The method can create new components dynamically. IMPORTANT: an element must be attached element in DOM.

ADD(declaration, [element]);
// @declaration {String/String Array}
// @element {jQuery Element/Component/Scope/Plugin) optional, a parent element (default: "document.body")

ADD('textbox__form.name__required:true;label:Test');

// or

ADD(['textbox__form.name__required:true;label:Test', 'checkbox__form.terms__label:I aggree with terms'], $('#tab'));

Method: AJAX()

The method creates an asynchronous request to a backend.

  • CORS is enabled on all URL addresses witch start http:// or https://
  • Default AJAX headers are stored in M.defaults.headers
  • Event for all AJAX errors: ON('error', function(response) {})
  • Event for all AJAX responses: ON('response', function(response) {})
  • JSON is parsed as JSON and JSON dates are converted to Date automatically
AJAX(options, [data], callback/path, [delay]);
// @options {String}
// @data {Object/String}
// @callback {Function} or @path {String}
// @delay {Number} Delay in milliseconds
// returns {jComponent}

// Without callback
// Response will be stored in "window.products.items" variable
AJAX('GET /api/products/', { search: 'Something' }, 'products.items');

// With a callback
AJAX('GET https://www.totaljs.com', function(value, err, response) {

    if (err) {
        // Error handling
    }

    // response.url      {String} URL address
    // response.process  {Boolean} Can disable future processing.
    // response.error    {Boolean} Is error?
    // response.upload   {Boolean} Is upload?
    // response.method   {String} Request method
    // response.data     {Object} Request data
    // response.response {String} Response content
    // response.status   {Number} HTTP status code
    // response.text     {String} HTTP status text
    // response.headers  {Object} Response headers

    console.log(value);
});

// Request with custom headers
AJAX('GET /api/products/ {"x-token":"CUSTOM HEADER"}', 'products.items');

// Environment usage
// e.g. ENV('productsurl', '/api/products/');
// +v11.0.0
AJAX('GET [productsurl]', 'products.items');
// [productsurl] will be replaced for "/api/products/"

// Enable CORS with credentials
// +v11.0.0
AJAX('!GET https://api.domain.com/products/', 'products.items');

// Request with a custom configuration
// Read more in AJAXCONFIG() method
// +v12.0.0
AJAX('GET (customConfig) /api/products/', 'products.items');
AJAX('GET (custom1, custom2, custom3) /api/products/', 'products.items');

Method: AJAXCACHE()

The method creates an asynchronous request to a backend with caching. Supports same features as AJAX().

AJAXCACHE(options, data, callback/path, expiration, [delay], [clear]);
// @options {String}
// @data {Object/String}
// @callback {Function} or @path {String}
// @expiration {String} In the form: "number [seconds, minutes, hours, days, weeks, months, years]"
// @delay {Number} Delay in milliseconds
// @clear {Boolean} Clears a previous cache
// returns {jComponent}

// Without callback
AJAXCACHE('GET /api/products/', null, 'products.items', '5 minutes');

// With a callback
AJAXCACHE('GET /api/products/', null, function(value, isFromCache) {
    console.log('Is from cache?', isFromCache);
}, '5 days');

Method: AJAXCACHEREVIEW()

The method reads a data from cache and creates independent asynchronous request to a backend with caching/comparing from the cache. Supports same features as AJAX().

AJAXCACHEREVIEW(options, data, callback/path, expiration, [delay], [clear]);
// @options {String}
// @data {Object/String}
// @callback {Function} or @path {String}
// @expiration {String} In the form: "number [seconds, minutes, hours, days, weeks, months, years]"
// @delay {Number} Delay in milliseconds
// @clear {Boolean} Clears a previous cache
// returns {jComponent}

// Without callback
AJAXCACHEREVIEW('GET /api/products/', null, 'products.items', '5 days');

// With a callback
AJAXCACHEREVIEW('GET /api/products/', null, function(value, isFromCache, areDifferent) {
    console.log('Is from cache?', isFromCache);
    console.log('Are data different?', areDifferent == true);
}, '5 days');

Method: AJAXCONFIG()

The method creates a schema of configuration for all AJAX() methods.

AJAXCONFIG(name, callback);
// @name {String}
// @fn {Function(req)}
// returns {jComponent}
// +v12.0.0

AJAXCONFIG('tokenizer', function(req) {
    req.headers['x-token'] = 'custom header';
    // req.type = 'GET';
});

// Usage in AJAX():
AJAX('GET (tokenizer) /api/products/', ...);

Method: BLOCKED()

The method can lock some code for a specific time. IMPORTANT: this method will store info about blocking in localStorage if the expiration is longer than 10 seconds.

BLOCKED(name, timeout);
// @name {String}
// @expiration {Number/String} +v12.0.6 supports environment values too
// returns {Boolean}

if (BLOCKED('submit', '3 seconds'))
    return;

// or

if (BLOCKED('submit', 3000))
    return;

Method: CACHE()

The method can set a value to cache or can get a value from cache. Cache keeps data in localStorage.

CACHE(key, [value], [expiration]);
// @key {String}
// @value {Object}
// @expiration {String} In the form: "number [seconds, minutes, hours, days, weeks, months, years]"
// returns {Object}

// Writing:
CACHE('key', 'value', '5 minutes'); 

// Reading:
console.log(CACHE('key'));

Method: CACHEPATH()

The method can store the last value of path in cache. If the page is refreshed the last value will be recovered.

CACHEPATH(path, [expiration], [rebind]);
// @key {String}
// @expiration {String} In the form: "number [seconds, minutes, hours, days, weeks, months, years]"
// @rebind {Boolean} Sets the value to path automatically (default: true)

CACHEPATH('user.name', '5 minutes');

// How to set a default values for the specific path?
MAKE('user', function(obj) {
    if (obj.name == null)
        obj.name = 'DEFAULT NAME';
});

Method: CAN()

The method checks dirty and valid states for all declared components on the path. If the method return true then the components are validated and some component has been changed by user (otherwise: false).

CAN(path, [except]);
// @path {String}
// @except {Array String} With absolute paths for skipping
// returns {Boolean}

if (CAN('users.form.*'))
    submit();

// or you can use it for disabling of buttons like this:
$('button.submit').prop('disabled', !CAN('users.form.*'));

// +v13.0.0 supports "except" flags
// @hidden - jComponent finds all hidden components
// @visible - jComponent finds all visible components
// @disabled - jComponent finds all components which have disabled inputs
// @enabled - jComponent finds all components which have enabled inputs
if (CAN('users.form.*', ['@visible', '@enabled'))
    submit();

Method: CHANGE()

+v15 The method can set a change for the path or can read the state, it works with dirty state.

CHANGE(path, [isChange]);
// @path {String}
// @isChange {Boolean} Can rewrite change (default: "true")
// returns {Boolean}

// Set the change for this path:
CHANGE('users.form.name', true);
CHANGE('users.form.name'); // same

// Unset the change for this path:
CHANGE('users.form.name', false);

Method: CHANGED()

+v15 The method reads a state, it works with dirty state.

CHANGED(path);
// @path {String}
// returns {Boolean}

// Reading state:
if (CHANGED('users.form.*')) {
    // Path has been changed
}

Method: CLEARCACHE()

+v14.1.1 The method clears a localStorage cache according to the MAIN.$localstorage property.

CLEARCACHE();

Method: CLEARSCHEDULE()

The method clears a scheduler generated by SCHEDULE().

CLEARSCHEDULER(id);
// @id {Number}

Method: clearTimeout2()

The method clears a registered by setTimeout2().

clearTimeout2(id);
// @id {Number}

Method: CLONE()

The method can clone an object to a new. v12.0.6 supports path as obj and the method clones an object according to the path.

CLONE(obj);
// @obj {Object/String}
// returns {Object}

var userA = { id: 1, name: 'Peter' };
var userB = CLONE(userA);
console.log(userA === userB);
// Output: false

userB.name = 'Lucia';
console.log(userA, userB);
// Output: { id: 1, name: Peter }, { id: 1, name: Lucia }


// +v12.0.6
var clone = CLONE('path.to.object');

Method: COMPILE()

The method compiles new injected jComponents. If some component appends new components dynamically then is needed to call COMPILE() method manually.

COMPILE([container]);
// @container {jQuery Element} Compiles components within container otherwise in the whole "document.body"

Method: COMPONENT()

The method registers a new reusable component.

COMPONENT(name, [config], declaration, [dependencies]);
// @name {String}
// @config {String} A default configuration
// @declaration {Function(instance, config)}
// @dependencies {Array String} +v12.0.4 optional, can contain URL addresses (script, styles, etc.) to all dependencies

COMPONENT('helloworld', 'fontsize:20px', function(self, config) {

    self.readonly();

    self.make = function() {
        self.html('HELLO WORLD!');
    };

    self.configure = function(key, value, init) {
        if (key === 'fontsize')
            self.css('font-size', value);
    });

});

Method: COMPONENT_CONFIG()

+v15 The method sets a default configuration for all components according to the selector.

COMPONENT_CONFIG(selector, config);
// @selector {String}
// @config {String/Object} A default configuration

// Possibilities:
COMPONENT_CONFIG('component-name', 'required:true;placeholder:Modified config');
COMPONENT_CONFIG('component-name .component-path', 'required:true;placeholder:Modified config');
COMPONENT_CONFIG('#component-id', 'required:true;placeholder:Modified config');
COMPONENT_CONFIG('#component-id .component-path', 'required:true;placeholder:Modified config');
COMPONENT_CONFIG('.component-path', 'required:true;placeholder:Modified config');
COMPONENT_CONFIG('*search-in-component-path', 'required:true;placeholder:Modified config');

COMPONENT_CONFIG(function(com) {
    // com === instance of the Component, but not fully initialized
    return true;
}, 'required:true;placeholder:Modified config');

Method: COMPONENT_EXTEND()

+v14 The method can extend a component by adding new features.

COMPONENT_EXTEND(name, [config], declaration);
// @name {String}
// @config {String} Optional, a default configuration
// @declaration {Function}

// Possibilities:
COMPONENT_EXTEND('component-name', 'name:Custom config;width:300', function(component) {
    component.element.append('<div>EXTENDED 1</div>');
});

COMPONENT_EXTEND('component-name', function(component) {
    component.element.append('<div>EXTENDED 2</div>');
});

Method: COPY()

+v16 The method copies all values from from object to to object.

COPY(obj_from, obj_to);
// @obj_from {Object}
// @obj_to {Object}
// returns {Object} "obj_to" object

Method: CREATE()

+v14.2.0 The method creates a watcher for all changes. I recommend to use this method for one-level properties (not for nested properties).

CREATE(path);
// @path {String}

CREATE(callback(path));
// @callback {Function(path)}

// With the path
var form = CREATE('form');
form.name = 'Peter';
// This line executes automatically "SET('form.name', 'Peter')" in the background

// With the callback
var obj = CREATE(function(property) {
    // obj has been changed
    console.log(obj);
});

obj.name = 'Peter';
// This line executes a callback automatically

Method: CSS()

The method creates inline CSS registered in the head tag. If you use id and execute CSS() twice then the previous styles will be removed.

CSS(value, [id]);
// @value {String} or {Array String}
// @id {String} Optional, CSS identificator

CSS('body { background-color: red; font-size: 18px; }\ndiv { background-color: black; color: white; }');

Method: DEFAULT()

The method sets default values for all declared components listen on the path. All components need to have declared data-jc-value="VALUE" attribute.

DEFAULT(path, [delay], [reset]);
// @path {String}
// @delay {Number} Optional, default: 0
// @reset {Boolean Optional, default true

DEFAULT('users.form.*');

Method: DISABLED()

The method checks dirty and valid states for all declared components on the path. If the method return false then the components are validated and some component has been changed by user (otherwise: true).

DISABLED(path, [except]);
// @path {String}
// @except {Array String} With absolute paths for skipping
// returns {Boolean}

if (!DISABLED('users.form.*'))
    submit();

// or you can use it for disabling of buttons like this:
$('button.submit').prop('disabled', DISABLED('users.form.*'));

// +v13.0.0 supports "except" flags
// @hidden - jComponent finds all hidden components
// @visible - jComponent finds all visible components
// @disabled - jComponent finds all components which have disabled inputs
// @enabled - jComponent finds all components which have enabled inputs
if (!DISABLED('users.form.*', ['@visible', '@enabled']))
    submit();

Method: EMIT()

The method emits event within events declared in jComponent library.

EMIT(name, [a], [b], [..n]);
// @name {String}
// @a {Object} Optional, additional argument
// @b {Object} Optional, additional argument
// @..n {Object} Optional, additional argument

EMIT('users.create', user);

Method: ENV()

The method gets/sets a value to/from jComponent environments.

ENV(key, [value]);
// @key {String}
// @value {Object} Optional
// returns {Object}

ENV('productsurl', '/api/products/');
console.log(ENV('productsurl'));
// Output: /api/products/

Method: ERRORS()

The method returns Array of all not validated components.

ERRORS(path, [except], [highlight]);
// @path {String}
// @except {Array String} Optional With absolute paths for skipping
// @highlight {Boolean} Optional, can highlight components (default: false)
// returns {Array Component}

console.log(ERRORS('users.form.*'));

// +v13.0.0 supports "except" flags
// @hidden - jComponent finds all hidden components
// @visible - jComponent finds all visible components
// @disabled - jComponent finds all components which have disabled inputs
// @enabled - jComponent finds all components which have enabled inputs
console.log(ERRORS('users.form.*', ['@visible', '@enabled']);

Method: EVALUATE()

The method can evaluate String expression as JavaScript code.

EVALUATE(path, expression, [path_is_real_value]);
// @path {String/Object} Can be object if "path_is_real_value" is "true"
// @expression {String} A condition.
// @path_is_real_value {Boolean} Optional, default: false
// returns {Boolean}

// With reading a value according to the "path"
var isTeenager = EVALUATE('users.form.age', 'value >= 10 && value <= 20');

// With a real value
var isTeenager = EVALUATE(15, 'value >= 10 && value <= 20', true);

Method: EXEC()

The method executes a method according to the path. It wont't throw any exception if the method not exist. Supports execution of:

  • method according the path
  • method in the controllers
  • events
  • supports environments
EXEC([wait], path, [a], [b], [..n]);
// @wait {Boolean} enables a waiter for the method instance (if method doesn't exist)
// @path {String}
// @a {Object} Optional, additional argument
// @b {Object} Optional, additional argument
// @..n {Object} Optional, additional argument

EXEC('users_refresh');
// Executes --> window.users_refresh();

EXEC('users_refresh', true);
// Executes --> window.users_refresh(true);

EXEC('#submit', true);
// Executes --> EMIT('submit', true);

EXEC('PLUGIN/method_name');
EXEC('@PLUGIN.method_name');

Method: EXEC2()

This method is same like EXEC() method but it returns a function. It must be used as a callback. All callback arguments will be used for the targeted method.

EXEC2([wait], path);
// @wait {Boolean} enables a waiter for the method instance (if method doesn't exist)
// @path {String}

// Example:
AJAX('GET /api/users/', EXEC2('process_users'));

Method: EXTEND()

The method extends a path by adding/rewrite new fields with new values.

EXTEND(path, value, [type/delay], [reset]);
// @path {String}
// @value {Object}
// @type/delay {String/Number} Optional, "value > 10" will be used as delay
// @reset {Boolean} Optional, default: false

EXTEND('users.form', { age: 35, alias: 'Peter' });

Method: EXTEND2()

+v16 The method extends a path by adding/rewrite new fields with new values and performs CHANGE().

EXTEND2(path, value, [type/delay]);
// @path {String}
// @value {Object}
// @type/delay {String/Number} Optional, "value > 10" will be used as delay

Method: FIND()

The method finds all component according to the selector.

FIND(selector, [many], [callback], [timeout]);
// @selector {String}
// @many {Boolean} Optional, output will be Array
// @callback {Function(response)} Optional and the method will be wait for non-exist components
// @timeout {Number} Optional, in milliseconds (default: 0)
// returns {Component} or {Array Component}

var com = FIND('component_name'); // FILTER: data-jc="component_name" or data-jc="component_name@..."
// Returns the only one component according to the component name

var com = FIND('component_name@1'); // FILTER: data-jc="component_name@1"
// +v14.0.0 Finds component according to the specific version

var com = FIND('component_name[path]'); // FILTER: data-jc="component_name" data-jc-path="path"
// Returns the only one component according to the component name and path

var com = FIND('#component_id'); // FILTER: data-jc-id="component_id"
// Returns the only one component according to the component id

var com = FIND('#component_id[path]'); // FILTER: data-jc-id="component_id" data-jc-path="path"
// Returns the only one component according to the component id and path

var com = FIND('.path'); // FILTER: data-jc-path="path"
// Returns the only one component according to the path

var com = FIND($(window)); // FILTER: jQuery container
// Returns the only one component according to the container as jQuery element
// +v11.4.0

var com = FIND('textbox', true);
// Returns Array of all components according to the selector

// Waiting for a component:
FIND('SELECTOR', function(component) {
    // This callback will be executed if the component will exist
    // @component {Component}
});

// Waiting for a component with 5 seconds timeout:
FIND('SELECTOR', function(component) {
    // This callback will be executed if the component will exist
    // @component {Component}
}, 5000);
// You can't process a timeout error (callback won't be executed).

Method: FORMATTER()

This method registers/evaluates a global formatter.

FORMATTER(value, path, type);

// Registers a new formatter
// All components use global formatters
FORMATTER(function(path, value, format) {
    // @path {String}
    // @value {Object}
    // @format {String}
    // MUST RETURN A VALUE!!!
    return value.toUpperCase(); 
});

// Executes a formatter for a value
console.log(FORMATTER('peter'));

Method: FN()

The method generates Function from expression of Arrow Function.

FN(expression);
// @expression {String}
// returns {Function}

var fn = FN('n => n.toUpperCase()');
console.log(fn('peter'));
// Output: PETER

Method: GET()

The method reads a value according to the path.

GET(path);
// returns {Object}

console.log(GET('common.page'));

Method: GETR()

+v15 The method reads value and resets all components according to the path.

GETR(path);
// returns {Object}

console.log(GETR('users.form.name'));

Method: GUID()

The method generates a unique String.

GUID([length]);
// @length {Number} Default: 10
// returns {String}

console.log(GUID());
// Output: 7a9zrsw2hi

Method: HASH()

The method generates Number hash sum.

HASH(value);
// @value {String}
// returns {Number}

console.log(HASH('Peter'));
// Output: 77005292

Method: IMPORT()

The method can import HTML content, JavaScript or CSS from external source.

  • supports re-type of extension https://maps.googleapis.com/maps/api/js?key=KEY .js
  • styles and scripts are inserted into the HTML head
  • supports environments
IMPORT(url, [target], [callback], [insert], [preparator]);
// @url {String} Relative or Absolute URL address
// @target {String} Optional, jQuery selector (default: "document.body")
// @callback {Function} Optional and the method will be wait for non-exist components
// @preparator {Function(content)} Optional, needs to return modified content

// Simple usage:
IMPORT('/templates/products.html');

// Content will be inserted to <div id="templates"></div>
IMPORT('/templates/products.html', '#templates');

// With a callback:
IMPORT('/templates/products.html', function() {
    // Done, template is imported and inserted
    // You can manipulate with DOM
});

// With a preparator function
IMPORT('/templates/products.html', NOOP, function(content, response) {
    return content.replace(/logo\.png/i, 'newlogo.png');
});

// Import e.g. scripts
IMPORT('https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.2/d3.min.js');

Method: IMPORTCACHE()

+v14.0.0. Is same as IMPORT() method but it needs to contain expire argument. This method can't cache plain css or js.

IMPORT(url, expire, [target], [callback], [insert], [preparator]);
// @url {String} Relative or Absolute URL address
// @expire {String} Expiration, e.g. 5 minutes
// @target {String} Optional, jQuery selector (default: "document.body")
// @callback {Function} Optional and the method will be wait for non-exist components
// @preparator {Function(content)} Optional, needs to return modified content

Method: INC()

The method increments a Number according to the path.

INC(path, value, [type/delay], [reset]);
// @path {String}
// @value {Number}
// @type/delay {String/Number} Optional, "value > 10" will be used as delay
// @reset {Boolean} Optional, default: false

// users.form.age = 35;
INC('users.form.age', 1);
// Output: users.form.age = 36;

Method: INC2()

+v16 The method increments a Number according to the path and performs CHANGE().

INC2(path, value, [type/delay]);
// @path {String}
// @value {Number}
// @type/delay {String/Number} Optional, "value > 10" will be used as delay

Method: INVALID()

The method highlights all components on the path as invalid.

INVALID(path, [except]);
// @path {String}
// @except {Array String} Can contain absolute paths for skipping (optional)

INVALID('users.form.*');

// +v13.0.0 supports "except" flags
// @hidden - jComponent finds all hidden components
// @visible - jComponent finds all visible components
// @disabled - jComponent finds all components which have disabled inputs
// @enabled - jComponent finds all components which have enabled inputs
console.log(INVALID('users.form.*', ['@visible', '@enabled']);

Method: LOG()

The method is a safe alias to console.log().

Method: MAKE()

+v15 This method can create an object.

MAKE(obj/path, fn, [update]);
// @path {Object/String}
// @fn {Function}
// @notify {Boolean} Optional, default "true"
// returns {String}

// Creates an object on the path "users.form" and notifies all components
MAKE('users.form', function(obj) {
    obj.name = 'Peter Širka';
    obj.age = 33;
});

console.log(users.form);
// Output: { name: 'Peter Širka', age: 33 }

Method: MAKEPARAMS()

+v15 This method can appends custom params to url.

MAKEPARAMS([url], values);
// @url {String} Optional, default: "location.href"
// @values {Object}
// returns {String}

console.log(MAKEPARAMS({ sort: 1, pricefrom: 300 }));
// Output: /?sort=1&price=300

console.log(MAKEPARAMS('/search/?q=Peter', { sort: 1, pricefrom: 300 }));
// Output: /search/?q=Peter&sort=1&pricefrom=300

Method: MEDIAQUERY()

This method registers a listener for specific size of the browser window or element. Read more in Responsive UI section.

MEDIAQUERY(query, [element], callback(w, h, type, id));
// @query {String} media CSS query string
// @element {jQuery Element} optional, needs to be jQuery element (default: "window")
// @callback {Function(w, h, type, id)} callback
// returns {Number} an idetificator of MediaQuery

// For the whole window
MEDIAQUERY('(min-width: 500px) and (max-width: 1024px) and (orientation: landscape)', function(w, h, type, id) {

    // w {Number} "window" width
    // h {Number} "window" height
    // type {String} display type, can be "xs", "sm", "md" or "lg"
    // id {Number} identificator of MediaQuery

    // This method will be executed if the MediaQuery condition will be valid for "window".

});

// For an element:
MEDIAQUERY('(min-width: 200px) and (max-width: 600px)', $('#panel'), function(w, h, type, id) {

    // w {Number} "element" width
    // h {Number} "element" height
    // type {String} display type, can be "xs", "sm", "md" or "lg"
    // id {Number} identificator of MediaQuery

    // This method will be executed if the MediaQuery condition will be valid for this element.

});

Method: MIDDLEWARE()

+v14.1.1 This method registers a new jRouting middleware. It's alias for NAV.middleware().

MIDDLEWARE(name, fn);
// @name {String} A middleware name
// @fn {Function(next)} Executor
// returns {NAV}

MIDDLEWARE('delay', function(next, options, roles) {
    // @next {Function} "next(false)" or "next(Error") won't be continue in processing
    // @options {Object} custom options defined in a route
    // @roles {String Array} roles defined in a route
    setTimeout(next, 1000);
});

Method: MODIFY()

+v15 The method performs SET() and CHANGE() together.

MODIFY(path);
// @path {String}
// @value {Object}
// @delay {Number} optional, default: 0


MODIFY('users.form.name', 'Peter');

// or

MODIFY('users.form', function(obj) {
    obj.name = 'Peter';
    obj.age = 33;
});

Method: MODIFIED()

The method returns all modified components by user on the path.

MODIFIED(path);
// @path {String}
// returns {Array String}

console.log(MODIFIED('users.form.*'));

Method: NEWTRANSFORM()

+v14.1.1 The method registers a new async transformation. Transformation can transform some data and it's evaluated via TRANSFORM(name, value, callback) global method.

NEWTRANSFORM(name, fn);
// @name {String}
// @fn {Function(value, next)}

NEWTRANSFORM('uppercase', function(value, next) {
    next(value.toUpperCase());
});

NEWTRANSFORM('twice', function(value, next) {
    next(value + value);
});

Method: NOOP

The method is an empty function and can be used as callback in some asynchronous method.

Method: NOTIFY()

The method notifies a setter in all components on the path.

NOTIFY(pathA, [pathB], [..pathN]);
// @pathA {String}
// @pathB {String} Optional
// @pathN {String} Optional

NOTIFY('users.form.name', 'users.form.age');

Method: NOTMODIFIED()

The method checks whether the value has not been modified on the path.

NOTMODIFIED(path, [value], [fields]);
// @path {String}
// @value {Object} Optional
// @fields {Array String} Optional, field names
// returns {Boolean}

// Is the "path.to.model" modified?
if (NOTMODIFIED('path.to.model')) {
    // The value according to the path is not modified
    return;
}

// Are fields "name" and "age" in "path.to.model" modified?
if (NOTMODIFIED('path.to.model', undefined, ['name', 'age'])) {
    // The value according to the path is not modified
    return;
}

// Compares a value according to the "modified.key"
// In other words: you can compare your own custom values
if (NOTMODIFIED('modified.key', your_custom_value)) {
    // The value according to the "modified.key" is not modified
    return;
}

Method: OFF()

The method unregisters an event listener.

OFF(name, [handler]);
// @name {String} Event name
// @callback {Function} Optional, event handler

OFF('response');
OFF('response', my_handler);

// Or for multiple events
OFF('name1 + name2 + name3');

Method: ON()

The method registers an event listener.

ON(name, handler];
// @name {String} Event name
// @callback {Function} Event handler

ON('response', function(response) {
    console.log(response);
});

// Or for multiple events
ON('name1 + name2 + name3', function() {

});

Method: PARSE()

The method parses JSON String to Object.

PARSE(value, [date]);
// @value {String}
// @date {Boolean} Auto-converting string dates to Date (default: "MAIN.defaults.jsondate")
// returns {Object}

Method: PARSER()

This method registers/evaluates a global parser.

PARSER(path, value, type);

// Registers a new formatter
// All components use global formatters
PARSER(function(path, value, format) {
    // @path {String}
    // @value {Object}
    // @format {String}
    // MUST RETURN A VALUE!!!!
    return value.toLowerCase(); 
});

// Executes a formatter for a value
console.log(PARSER('PETER'));

Method: PING()

The method pings a URL address. Each request contains additional header X-Ping with the current location).

  • +v11.0.0 important: the response will be evaluated as JavaScript code
  • +v11.0.0 additional request PING data are stored in MAIN.defaults.pingdata
  • +v11.2.0 supports environments variables
  • +v14.1.1 supports execute argument (default: false) for immediate invocation
  • +v14.1.1 adds new headers x-cookies and x-referrer
PING(url, [delay], [execute]);
// @url {String}
// @delay {Number} Optional, in milliseconds (default: "30000")
// @execute {Boolean} Optional (default: false)
// returns {Object}

PING('/api/ping');

// or with another method than GET
PING('POST /api/ping');

// or with environment key:
PING('[pingurl]');

Method: PLUGIN()

The method can register or get a plugin. Read more about plugins in Plugins section.

PLUGIN(name, [declaration]);
// @name {String}
// @declaration {Function}
// returns {Plugin}

// Registers a plugin:
PLUGIN('Users', function(instance) {
    // New instance of the 
});

// Gets a plugin
var users = PLUGIN('Users');

Method: PUSH()

The method pushs a new item into the Array according to the path.

PUSH(path, value, [type/delay], [reset]);
// @path {String}
// @value {Object} or {Array}
// @type/delay {String/Number} Optional, "value > 10" will be used as delay
// @reset {Boolean} Optional

// Single item:
PUSH('users.form.tags', 'Total.js');

// Or Array:
PUSH('users.form.tags', ['Node.js', 'Total.js']);

Method: PUSH2()

+v16 The method pushs a new item into the Array according to the path and performs CHANGE().

PUSH2(path, value, [delay], [reset]);
// @path {String}
// @value {Object} or {Array}
// @type/delay {String/Number} Optional, "value > 10" will be used as delay

Method: READPARAMS()

This method parses URL arguments from the current URL address.

READPARAMS([query]);
// @query {String} Optional, custom URL (default: "location.href")
// returns {Object}

console.log(READPARAMS('/search/?q=Peter'));
// Output: { q: "Peter" }

Method: RECONFIGURE()

+v13.0.0 reconfigures all components according to the selector.

RECONFIGURE(selector, config);
// @selector {String}
// @config {String/Object}

RECONFIGURE('form', 'title:Edit product;width:800');
RECONFIGURE('form', { title: 'Edit product' });

Method: REMOVECACHE()

The method removes item(s) from cache.

REMOVECACHE(key, [isSearching]);
// @key {String}
// @isSearching {Boolean} Optional, default: "false"

REMOVECACHE('myKey'); 

// All keys which contain "home":
REMOVECACHE('home', true);

Method: RESET()

The method resets dirty and valid state in all components on the path.

RESET(path, [delay]);
// @path {String}
// @delay {Number} Optional, in milliseconds (default: 0)

RESET('users.form.*');

Method: SCHEDULE()

The method resets dirty and valid state in all components on the path.

Types:

  • input value has been changed by input
  • manually value has been changed by e.g. SET(), UPDATE(), PUSH(), etc.
  • init from initialization of the component
SCHEDULE(selector, type, delay, callback);
// @selector {String} Selector within components according to the "FIND()" method
// @type {String} Can be: "input", "manually", "init"
// @delay {String} Last update time and in the form: "number [seconds, minutes, hours, days, weeks, months, years]"
// @callback {Function(component}
// returns {Number} Scheduler identificator like "setTimeout()"

// Evaluates the callback after 5 minutes if the value according to the "data-jc-path" has been changed by "input"
SCHEDULE('.find-by-component-path', 'input', '5 minutes', function(component) {
    AJAX('GET /api/refresh/', component.path);
});

// Evaluates the callback after 3 seconds if the value according to the "data-jc-path" has been changed manually by developer
SCHEDULE('#find-by-component-id', 'manually', '3 seconds', function(component) {
    AJAX('GET /api/refresh/', component.path);
});

// Evalutes the callback 1 hour from initialization of the component
var task = SCHEDULE('find-by-component-name', 'init', '1 hour', function(component) {
    AJAX('GET /api/refresh/', component.path);
});

// Removing existing schedulers:
CLEARSCHEDULE(task);

Method: SCHEMA()

The method registers a schema or reads existing. The schema can be used for forms for declaring default values.

SCHEMA(name, [declaration]);
// @name {String}
// @declaration {Object} Optional

// Registers a new schema with raw object
SCHEMA('User', { firstname: 'Peter', lastname: 'Širka', note: 'default values' });

// Creates object according to the schema
var userA = SCHEMA('User');
var userB = SCHEMA('User');

console.log(userA === userB);
// Output: false

console.log(userA);
// Output: { firstname: Peter, lastname: Širka, note: default values }

Method: SCOPE()

The method can extend existing controller's scope. If the controller doesn't exist the method is waiting on it (otherwise: scopeFn function is evaluated when the controller exists).

SCOPE(name, [scopeFn]);
// @name {String}
// @scopeFn {Function}

SCOPE('UserController', function(instance, scope, element) {
    // Controller's scope
});

Method: SCROLLBARWIDTH()

v12.0.0 The method gets a width of scrollbar and caches it for future usage in the current session.

SCROLLBARWIDTH();
// Returns {Number}

Method: SET()

The method sets a new value according to the path.

SET(path, value, [type/delay], [reset]);
// @path {String}
// @value {Object}
// @type/delay {String/Number} Optional, number > 10 will be used as a delay
// @reset {Boolean} Optional, default: false

SET('users.form.age', 30);

Method: SET2()

v16 The method sets a new value according to the path and performs CHANGE() for all components which are listening on the path.

SET2(path, value, [type/delay]);
// @path {String}
// @value {Object}
// @type/delay {String/Number} Optional, number > 10 will be used as a delay

SET2('users.form.age', 30);

Method: setTimeout2()

The method is improved setTimeout method. This method cancels a previous unexecuted call.

setTimeout2(key, fn, timeout, [limit], [param]);
// @key {String}
// @fn {Function(param)}
// @timeout {Number}
// @limit {Number} Optional, a maximum clear limit (default: 0)
// @param {Object} Optional, additional argument
// return {Number}

setTimeout2('key', function() {
    console.log('DONE');
}, 100);

setTimeout2('key', function() {
    console.log('DONE');
}, 100);

setTimeout2('key', function() {
    console.log('DONE');
}, 100);

// Output: DONE

// Clearing of registered setTimeout2():
var id = setTimeout2('something', NOOP, 1000);
clearTimeout2(id);

Method: SETTER()

The method can set a new value to the specific method in components.

SETTER([wait], selector, propOrMethod, [argA], [argB], [..argN]);
// @wait {Boolean} Optional, can it wait for non-exist components?
// @selector {String}
// @propOrMethod {String} Property or Method name (can't be nested)
// @argA {Object} Optional, additional argument
// @argB {Object} Optional, additional argument
// @..argN {Object} Optional, additional argument
// returns {SETTER}

SETTER('#loading', 'hide', 1000);
// Executes --> FIND('#loading').hide(1000);

SETTER('textbox', 'set', 'NEW VALUE');
// Executes --> FIND('textbox').set('NEW VALUE');

SETTER('textbox@1', 'set', 'NEW VALUE');
// Executes --> FIND('textbox@1').set('NEW VALUE');

SETTER(true, 'loading', 'show');
// +v9.0.0 It will waits for "lodaing" component and then executes --> FIND('loading').show();

SETTER($('#container'), 'reconfigure', 'icon:home');
// +v11.4.0 supports jQuery element or DOM element

Method: SKIP()

+v13.0.0 The method skips component.setter for future update. It's incremental.

SKIP(pathA, [pathB], [pathN]);
// @pathA {String} Absolute path according to the component "data-jc-path"
// @pathB {String} Optional, absolute path according to the component "data-jc-path"
// @pathN {String} Optional, absolute path according to the component "data-jc-path"

SKIP('users.form.firstname', 'users.form.lastname');

// Or you can use multiple paths in the one path:
SKIP('users.form.firstname, users.form.lastname', 'users.stats.orders, users.stats.logins');

Method: STRINGIFY()

The method serializes Object to JSON.

STRINGIFY(obj, [compress], [fields]);
// @obj {Object}
// @compress {Boolean} Optional, default: "MAIN.defaults.jsoncompress"
// @fields {Array String} or {Object} Optional

STRINGIFY({ name: 'Peter', age: 33 });
// Output: {"name":"Peter","age":33}

// With enabled compression:
STRINGIFY({ name: '  Peter  ', age: 33, something: null }, true);
// Output: {"name":"Peter","age":33}

// With custom fields (Array):
STRINGIFY({ name: '  Peter  ', age: 33, something: null }, true, ['age']);
// Output: {"age":33}

// With custom fields (Object):
STRINGIFY({ name: '  Peter  ', age: 33, something: null }, false, { name: false });
// Output: {"age":33,"something":null}

Method: TRANSFORM()

+v14.1.1 The method performs some transformation registered via NEWTRANSFORM() global method.

TRANSFORM('uppercase', 'peter', function(value) {
   console.log(value);
   // output: PETER
});

// You can execute multiple transformations:
TRANSFORM('uppercase, twice', 'peter', function(value) {
   console.log(value);
   // output: PETERPETER
});

// or
TRANSFORM('uppercase, twice', 'peter', 'path.to.bind');

// or for AJAX with a path
AJAX('GET /api/something/', TRANSFORM('uppercase, twice', 'path.to.bind'));

// or for AJAX with a function
AJAX('GET /api/something/', TRANSFORM('uppercase, twice', function(value) {
    console.log(value);
}));

Method: TOGGLE()

+v16 The method performs toggle for the path. A value must be Boolean.

TOGGLE(path, [type/delay], [reset]);
// @path {String}
// @type/delay {String/Number} Optional, "value > 10" will be used as delay
// @reset {Boolean} Optional, resets state of all components

TOGGLE('form.terms');

Method: TOGGLE2()

+v16 The method performs toggle for the path. A value must be Boolean.

TOGGLE2(path, [type/delay]]);
// @path {String}
// @type/delay {String/Number} Optional, "value > 10" will be used as delay
// @reset {Boolean} Optional, resets state of all components

TOGGLE2('form.terms');

Method: TOGGLE2()

+v16 The method performs toggle for the path and performs CHANGE() for all components which are listening on the path. A value must be Boolean.

TOGGLE2(path, [type/timeout]);
// @path {String}
// @type/delay {String/Number} Optional, "value > 10" will be used as timeout

TOGGLE2('form.terms');

Method: VALIDATE()

The method validates all components on the path.

VALIDATE(path, [except]);
// @path {String}
// @except {Array String} Optional With absolute paths for skipping
// returns {Boolean}

var valid = VALIDATE('users.form.*');
console.log(valid);

Method: VERSION()

+v14.0.0 The method sets a version for specific components.

VERSION(a, [b], [n]);
// @a {String} name + version
// @b {String} Optional
// @n {String} Optional

VERSION('textbox@1', 'dropdown@1');

Method: UPLOAD()

The method can upload multipart/form-data asynchronous.

UPLOAD(url, data, path/callback, [delay], [progress]);
// @url {String}
// @data {FormData}
// @path/callback {String} or {Function(response, err, output)}
// @delay {Number} Optional, delay to upload
// @progress {String} or {Function(percentage, speed, remaining)}

var data = new FormData();
data.append('file', files[0]);

// Basic usage:
UPLOAD('/api/logo/', data, 'path.to.response');

// or
UPLOAD('/api/logo/', data, function(response, err) {
    console.log(response);
});

// With progress bar
UPLOAD('/api/logo/', data, function(response, err) {
    console.log(response);
}, 'path.to.progress.percentage');

// or
UPLOAD('/api/logo/', data, function(response, err) {
    console.log(response);
}, function(percentage, speed, remaining) {
    console.log('Upload: ' + percentage);
});

Method: UPDATE()

The method updates all components on the entire path.

UPDATE(path, [type/delay], [reset]);
// @path {String}
// @type/delay {String/Number} Optional, "value > 10" will be used as delay
// @reset {Boolean} Optional, default: false

users.form.name = 'Peter';
users.form.age = 30;
UPDATE('users.form');

// +v14.1.1 with custom setter type
UPDATE('users.form', 'mytype');

Method: UPDATE2()

+v16 The method updates all components on the entire path and performs CHANGE().

UPDATE2(path, [type/delay]);
// @path {String}
// @type/delay {String/Number} Optional, "value > 10" will be used as delay

Method: UPTODATE()

The method can perform browser reload after some time.

  • +v14.1.1 adds condition argument
UPDATE(period, [url], [callback], [condition]);
// @period {String} In the form: "number [seconds, minutes, hours, days, weeks, months, years]"
// @url {String} Optional, otherwise will refreshed the current location
// @callback {Function} Optional, after 5 seconds will be performed reload
// @condition {Function} Optional, must return {Boolean}

UPTODATE('1 day');
UPTODATE('1 day', '/products/');

// +v14.1.1
UPTODATE('1 day', function(timeout) {
    // Prevents reloading
    clearTimeout(timeout); 
}, function() {
     // condition
    // it means: can I perform reloading?
    return true;
});

Method: WAIT()

The method can wait for a feature.

WAIT(path/fn, callback, [interval], [timeout]);
// @path/fn {String} or {Function}
// @callback {Function}
// @interval {Number} Optional, in milliseconds (default: 500)
// @timeout {Number} Optional, a timeout (default: 0 - disabled)

// With a path defined in "window" scope:
WAIT('d3', function(err) {
    if (err) {
        console.log(err);
    } else {
        console.log('D3 is initialized');
    }
});

// With a function:
WAIT(function() {
    return window.d3;
}, function(err) {
    if (err) {
        console.log(err);
    } else {
        console.log('D3 is initialized');
    }
});

Method: WATCH()

The method registers a new watcher for a specific path.

WATCH(path, handler, [init]];
// @path {String} Event name
// @handler {Function} Event handler
// @init {Boolean} Optional, it evaluates path now (default: false)

WATCH('path.to.model', function(path, value, type) {

    // Arguments description:
    // @path {String} Path which has been changed
    // @value {Object} New value
    // @type {Number} 0: init, 1: manually, 2: input, 3 default

    console.log('NEW VALUE', value);
});

// with the evaluation:
WATCH('path.to.model', function(path, value, type) {
    console.log('NEW VALUE', value);
}, true);

// or for multiple paths:
WATCH('path1 + path2 + path3', function(path, value, type) {

});

Method: USAGE()

This method returns last usage components.

USAGE(type, expire, [path], [callback]);
// @type {String} Can be "init", "manually", "input" or "custom"
// @expire {String/Number}, for example "5 minutes"
// @path {String} Optional, for example "users.form.name"
// returns {Array Component} or {jComponent}

console.log(USAGE('init', '5 minutes'));
// Returns {Array Component}

USAGE('init', '5 minutes', function(component) {
    console.log(component);
});