altersoftware.IT
altersoftware.IT

:: libs :: js-as-core

AS object, exposes methods

Basic JavaScript library from AlterSoftware, used also by other JavaScript modules.

Current version: 1.51 (2020-11-25)

Load

Basic usage, loading from Altersoftware CDN:

<script type="text/javascript" src="https://cdn.altersoftware.org/js-as-core/as-core.js" charset="UTF-8"></script>

Other Altersoftware modules can be loaded together, using modules comma separated attribute in the script tag.

E.g. if we want to load js-as-labels and js-as-form we can use:

<script type="text/javascript" modules="labels, form" src="https://cdn.altersoftware.org/js-as-core/as-core.js" charset="UTF-8"></script>

Modules are loaded in declaration order, beware of prerequisites — in this case js-as-labels must be loaded before js-as-form.

Download

All downloads are refreshed daily from the latest stable branch of Altersoftware GIT repository.

Index

Core types prototype extension

Array

Array().clone()

Creates a clone of a data array, including neted arrays and/or objects.

Note: Array shouldn't contain any code reference, leafs can only be string or numbers.

Number

Number().smartSize()

Converts bytes integer into smart IT representations

console.log(Number(12334445566).smartSize());
// returns --> "11.5 GB"

console.log(Number(4200).smartSize());
// returns --> "4.1 kB"

String

String().dehtml()

Returns the string removing HTML tags and quotes, if any.

Use:

console.log('Hello, <b>today</b> 3 > 2 is "true"!'.dehtml());

// returns --> "Hello, today 3 > 2 is true !"

String().escape()

Returns the string escaping HTML tags, if any.

Use:

console.log('Hello, <b>today</b> 3 > 2 is "true"!'.escape());

// returns --> "Hello, &lt;b&gt;today&lt;/b&gt; 3 &gt; 2 is \"true\"!"

String().escapeDate()

Returns the string parsing it as a SQL timestamp, in a smart format.

Use:

console.log('2021-01-15 03:05:10'.escapeDate());

// returns --> "15.1.21, 3:05"

String().shorten()

Returns the string shortened.

A single object parameter is allowed, for options in the form of key/value.
Options and all keys are optional, and have a default value.

console.log('Hello, <b>today</b> 3 > 2 is "true"!'.shorten());
// returns --> "Hello, <b>today</b> 3 > 2 is \"true\"!"

console.log('Hello, <b>today</b> 3 > 2 is "true"!'.shorten({html:true, max:16});
// returns --> "Hello, today 3…"

String().trim()

Returns the string trimming leading and trailing white spaces, if any.

AS functions

AS.addClass( obj, className )

Adds a class to one or more DOM nodes.

Requires two parameters:

  1. obj (mandatory) — a DOM Node, an array of DOM Nodes, a NodeList or a CSS selector string.
  2. className (String, mandatory) — the name of the class to be added to the node(s).

Note: in case jQuery is loaded this method relies on $(obj).addClass(className)

AS.args2array( argumentsOrNodeList )

Returns the arguments of a function or a NodeList as a regular array.

function delayer() {
    // Call a funcion in timeout
    // first argument: function name
    // then every other argument.
    let ags = AS.args2array(arguments);
    let funcName = ags.shift();
    return setTimeout( function(){ window[funcName].apply(window,ags); }, 100);
}
// or the equivalent of AS.getNodes('div'):
let arrayOfNodes = AS.args2array( document.querySelectorAll('div') );

AS.def.xxx( obj )

Returns default value for a tested object.

AS.getClasses( obj )

Accepts single parameter, a DOM node.

Returns an array of class names.

AS.getNodes( param )

Accepts a single parameter, returns an array of DOM nodes.

param (mandatory) can be a DOM Node, an array of DOM Nodes, a NodeList or a CSS selector string.

AS.generateId( [base] )

Return a random generated ID, optionally with a “base”.

console.log(AS.generateId());
// returns something like: "asTempId_ygDMuUTN1UTNzEDNyYDO3MjMMC41NDQ0NjE0ODExNTI5MDg4"

console.log(AS.generateId('tempDiv'));
// returns something like: "tempDiv_gTNy4CO1UjNwcDNzITM5AjNMC4yODAyMzY0MjI4MzIwOTMxNg"

AS.hasClass( obj, className )

Returns true if obj has class className, false otherwhise.

Requires two parameters:

  1. obj (mandatory) — a DOM Node, an array of DOM nodes, a NodeList or a CSS selector string.
  2. className (String, mandatory) — the name of the class to be removed from the node(s).

If multiple nodes are passed (as a NodeList, through selector or in an array) returns true if at least one of the nodes has class className.

AS.id( param )

Returns the Node id attribute of param, in case it’s missing generates a new ID and returns it.

param (mandatory) can be a DOM Node, an array of DOM Nodes, a NodeList or a CSS selector string.
If multiple nodes are passed (as a NodeList, through selector or in an array) only the first node is considered.
In case param (or its first element) isn’t a Node, returns false.

AS.loadCSS( css )

Loads the css file(s) by appending the node(s) to the HEAD element.

Checks for duplicates, wraps load errors (reported in console).

Returns the number of files loaded.

css parameter can be:

AS.loadJS( js )

Loads the js file(s) by appending the node(s) to the HEAD element.

Checks for duplicates, wraps load errors (reported in console).

Returns the number of files loaded.

js parameter can be:

AS.path( key )

Set path strings, or return specific path strings.

Default values are:

{
    webroot : '/',
    currentstyle : '/style:default',
    allstyles : '/style:'
}

If the argument is a string it returns the corresponding path.
If the argument is a key/value Oject it's used to set path values, and returns the path Object.

path values can be defined in the page also using META tags, e.g.:

<meta name="AS.path.webroot" content="/myapp" />
<meta name="AS.path.currentstyle" content="/myapp/styles/mystyle" />
<meta name="AS.path" allstyles="/myapp/styles/" labels="/myapp/locales/mypage-" />

AS.rmClass( obj, className )

Removes a class from one or more DOM nodes.

Requires two parameters:

  1. obj (mandatory) — a DOM Node, an array of DOM nodes, a NodeList or a CSS selector string.
  2. className (String, mandatory) — the name of the class to be removed from the node(s).

Note: in case jQuery is loaded this method relies on $(obj).removeClass(className)

AS.toggleClass( obj, className )

Toggles a class from one or more DOM nodes.

Requires two parameters:

  1. obj (mandatory) — a DOM Node, an array of DOM nodes, a NodeList or a CSS selector string.
  2. className (String, mandatory) — the name of the class to be toggled in the node(s).

Note: in case jQuery is loaded this method relies on $(obj).toggleClass(className)

AS.test.xxx()

Tests window/environment, returns a Boolean.

AS.test.xxx( obj )

Tests if a variable is a specific format, returns a Boolean.

Please note:

AS.version()

Returns version number.

Animation effects

Except for .style.display set to none, ensure that the node(s) is/are visible before invoking the transition, meaning: visible if style.display is empty, otherwise the transition won’t have any visible effect on a non-visible element.

Check for:

The node(s) must be visible right before invoking the transition (both in and out transitions).
In case change node’s .style properties value before invoking the transition.

At the end of the transition Node’s style.display is set to:

AS.fadeIn( Node(s), […] )

Performs the “fade in” animation of an HTML Element (or elements).

The first parameter is a DOM Node, an array of DOM nodes, a NodeList or a CSS selector string.

Following parameters are optional, and regardless of the order they can be:

Reverse: AS.fadeOut()

AS.fadeOut( Node(s), […] )

Performs the “fade out” animation of an HTML Element (or elements).

Uses the same parameters as AS.fadeIn()

AS.slideDown( Node(s), […] )

Performs the “slide down” animation of an HTML Element (or elements).

The first parameter is a DOM Node, an array of DOM nodes, a NodeList or a CSS selector string.

Following parameters are optional, and regardless of the order they can be:

Reverse: AS.slideUp()

AS.slideIn( Node(s), […] )

Performs the “slide in” animation of an HTML Element (or elements).

The first parameter is a DOM Node, an array of DOM nodes, a NodeList or a CSS selector string.

Following parameters are optional, and regardless of the order they can be:

Reverse: AS.slideOut()

AS.slideOut( Node(s), […] )

Performs the “slide out” animation of an HTML Element (or elements).

Uses the same parameters as AS.slideIn()

AS.slideUp( Node(s), […] )

Performs the “slide up” animation of an HTML Element (or elements).

Uses the same parameters as AS.slideDown()

Dealing with cookies

as-core offers a few facilities for cookies management.

AS.getCookie( cookieName )

Returns a string with the URI-decoded value of the cookie named cookieName.

AS.getCookies()

Returns an object with cookies.

Object keys are the names of the cookies, values are the URI-decoded related string values.

AS.setCookie( name, [value], [options] )

Sets the value of cookie name to value (string value).

value defaults to empty string, and is automatically URI-encoded.

options is an optional object, that can have the following optional keys:

Returns the string used to set cookie.

Note: if domain is specified the coookie by default is set on both the domain and its subdomains, e.g.: it’s set with a leading .

AS.rmCookie( name, [options] )

Deletes the cookie name, if any.

See AS.setCookie() for optional options.

Warning: to succesfully delete a cookie path and domain values must match.

Note: cookies deletion is operated twice, using domain both with and without a leading .
This workaround permits to delete also cookies set by Apache RewriteRules using [CO=…] flag, as well as cookies set on domain and subdomains.
If no domain is provided it’s operated without domain and with domain '.' + location.hostname

Dealing with events

AS object offers a few methods wrapping standard event commands:

AS.addEvent( DOMnode, eventType, function, [key] )

Adds an event listener to DOMnode, if possible.

Works exactly like DOMnode.addEventListener( eventType, function ), actually wraps it, in addition:

Notes:

AS.addEventIfAny( DOMnode, eventType, function, [key] )

Adds an event listener to DOMnode, if possible, only if there’s not an event of type eventType already defined for DOMnode with any key.

Notes:

AS.addEventIfNot( DOMnode, eventType, function, [key] )

Adds an event listener to DOMnode, if possible, only if there’s not an event of type eventType already defined for DOMnode with key.

Notes:

AS.listEvents( DOMnode, [eventType], [key] )

If eventType and key are provided returns an array of function event handlers defined for that DOMnode on eventType for key.

If eventType is provided returns an object: keys are key properties, each value is the related above mentioned array.

In case eventType and key aren’t provided returns an object: keys are eventTypes, each value is the related above mentioned object.

Notes:

AS.triggerEvent( DOMnode, eventType, [data] )

Triggers an event, standard or custom, on DOMnode.

Custom events must contain the ':' character to be recognized, it’s good practice to use it as a kind of "namespace" (e.g.: as:change).

In case a CustomEvent is triggered it can optionally carry additional data, that will be received by event handlers in event.detail property.

Dealing with MutationObserver

MutationObserver introduces a new approach to Mutation Events.

Using AS.observe() and AS.observeAttr() methods makes it easier to handle with mutations and related notifications.

Both AS.observe() and AS.observeAttr() can be triggered on a Node, on an array of Nodes, on a NodeList or using a CSS selector string.

Both AS.observe() and AS.observeAttr() return an array of objects with properties node and observer, to stop it don’t forget to use observer.disconnect().
The return value is always an array, also on a single node, because they accept multiple nodes.

AS.observe( params )

Creates and starts MutationObserver object(s).

params is a mandatory object parameters object with the following keys:

Returns an array of objects with properties node and observer, to stop it don’t forget to use observer.disconnect().

AS.observeAttr( params )

An efficient wrap to observe DOM node(s) attributes.

params is a mandatory object parameters object with the following keys:

Returns an array of objects with properties node and observer, to stop it don’t forget to use observer.disconnect().

When mutations happen they’re grouped together, filtered by attribute(s) (if any).

Only one cumulative notification per node is sent back to params.callback, with 3 parameters:

  1. The DOM node that was changed
  2. An object with mutated attributes:
    • the key is the name of the attribute — note that class becomes className.
    • the value is an object with attributes:
      • attribute, the attribute name (in this case className remains class)
      • mutation, the MutationRecord object
    • In case of multiple mutations on the same attribute only reports the last occurrence.
  3. The observer object

AS.reflectAttr( sourceNode, observedNode, attributeName, [setProperty] )

A convenient shortcut to have a DOM node reflecting another DOM node attribute (e.g.: className, value, disabled etc.)

Parameters:

Methods available if jQuery is loaded before as-core.js

$.postJSON( url, [data], [callback] )

Extends jQuery with the $.postJSON() method.

This method invokes a remote method and passes in the body of the request the serialized JSON of parameters, rather than a regular form.
contentType of the request is set to application/json,

Parameters are:

  1. url (string, mandatory) — the URL of the resource to be POSTed
  2. data (object, optional) — the key/value object of parameters
  3. callback (function, optional) — if defined the responde will be passed to such function

AS.id( obj )

Returns the ID of an object, in case it hasn't an ID attribute it's generated on the fly and returned.

Accepts one or two parameters:

  1. object (DOM or jQuery object, mandatory) — the object.
  2. idBase (string, optional) — In case the ID should be generated this will be the ID base passed to AS.generateId().

AS.toj( param, [context] )

Returns a jQuery object (if exists) or false.

Accepts one or two parameters:

  1. identifier (string, or DOM or jQuery object, mandatory) — In case of string it's expected to be the ID of the node, with or without the leading #.
  2. context (string, or DOM or jQuery object, optional) — The scope of the object search is limited to this object context. In case of String follows the same rules as identifier.

AS.ws( uri, [data], [callback], [type] )

POSTs to a remote WebService and returns the response to a callback.

Parameters accepted are up to 4, in whatever order:

  1. URI (String, mandarory) — The URI of the remote WebService (relative is fine).
  2. data (key/value object, optional) — The JavaScript object with parameters. In case data is a String with serialized FORM data provide it only after the URI.
  3. callback (function, optional, default: no callback) — The function object that will receive the response.
  4. type (String, optional, default: type:post) — Only accepts literal values type:post, type:get or type:json. Use this parameter with type:json to force the use of $.postJSON().

In case data is undefined then a rnd parameter is added (to avoid cache issues) populated with a random number.

Note: for both POST and GET data will be a plain key/value representation, like in a form.
When data parameter is a JavaScript object, then in case one of its keys starts with "j" and its value is an object (rather than to a scalar value, Number or String), then the related value will become the JSON String of the object.
This can be very useful if you want to pass to the remote WebService a parameter containing a JSON object.

AS.wslist( array )

Accepts an array of array.

Each array item is an array with up to 4 entries (AS.ws() parameters) that will be used to invoke sequentially AS.ws().

When a request is fullfilled, including the callback if any, the following WebService is processed.

Version history

This is a compact basic toolbox, doesn’t change very often.