Members
fetchOptions
Example
make POST default method
fetchOptions.method = "POST"
await afetch("url.com")
Methods
$(selector, docopt) → {null|HTMLElement}
- Description:
An alias to document.querySelector, doc can be an Element, empty or non-string selectors will return null
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
selector |
string | ||
doc |
HTMLElement |
<optional> |
Returns:
| Type | Description |
|---|---|
| null | HTMLElement |
Example
var el = app.$("#div")
$all(selector, docopt) → {null|Array.<HTMLElement>}
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
selector |
string | ||
doc |
HTMLElement |
<optional> |
Returns:
| Type | Description |
|---|---|
| null | Array.<HTMLElement> |
Example
Array.from(app.$all("input")).find((el) => !(el.readOnly || el.disabled || el.type == "hidden"));
$append(element, template, setupopt)
- Description:
Append nodes from the template to the given element, call optional setup callback for each node.
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
element |
string | HTMLElement | ||
template |
string | HTMLElement | can be a string with HTML or a template element. |
|
setup |
function |
<optional> |
Example
app.$append(document, "<div>...</div>")
$attr(element, attr, valueopt) → {undefined|any}
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
element |
HTMLElement | string | ||
attr |
string | ||
value |
any |
<optional> |
|
Returns:
| Type | Description |
|---|---|
| undefined | any |
$data(element, levelopt) → {Proxy|undefined}
- Description:
Return component data instance for the given element or the main component if omitted. This is for debugging purposes or cases when calling some known method is required.
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
element |
string | HTMLElement | ||
level |
number |
<optional> |
if is not a number then the closest scope is returned otherwise only the requested scope at the level or undefined. This is useful for components to make sure they use only the parent's scope for example. |
Returns:
| Type | Description |
|---|---|
| Proxy | undefined |
to get the actual object pass it to Alpine.raw(app.$data()) |
$elem(name, optionsopt)
- Description:
Create a DOM element with attributes, -name means style.name, .name means a property name, all other are attributes, functions are event listeners
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
name |
string | ||
...args |
any | object |
<optional> |
|
options |
object |
<optional> |
Examples
$elem("div", "id", "123", "-display", "none", "._x-prop", "value", "click", () => {})
Similar to above but all properties and attributes are taken from an object, in this form options can be passed, at the moment only options for addEventListener are supported.
$elem("div", { id: "123", "-display": "none", "._x-prop": "value", click: () => {} }, { signal })
$empty(element, cleanupopt) → {HTMLElement}
- Description:
Remove all nodes from the given element, call the cleanup callback for each node if given
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
element |
HTMLElement | string | ||
cleanup |
functions |
<optional> |
Returns:
| Type | Description |
|---|---|
| HTMLElement |
$event(element, name, detailopt)
- Description:
Send a CustomEvent using DispatchEvent to the given element, true is set to composed, cancelable and bubbles properties.
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
element |
HTMLElement | ||
name |
string | ||
detail |
object |
<optional> |
$off(element, event, callback)
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
element |
HTMLElement | ||
event |
string | ||
callback |
function | ||
...args |
any |
<optional> |
additional params to removeEventListener |
$on(element, event, callback)
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
element |
HTMLElement | ||
event |
string | ||
callback |
function | ||
...args |
any |
<optional> |
additional params to addEventListener |
Example
app.$on(window, "popstate", () => { ... })
$param(name, dfltopt) → {string}
- Description:
Returns a query parameter value from the current document location
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
name |
string | ||
dflt |
string |
<optional> |
Returns:
| Type | Description |
|---|---|
| string |
$parse(html, formatopt)
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
html |
string | ||
format |
string |
<optional> |
defines the result format:
|
Example
document.append(...$parse("<div>...</div>"), 'list'))
$ready(callback)
- Description:
Run callback once the document is loaded and ready, it uses setTimeout to schedule callbacks
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
callback |
function |
Example
app.$ready(() => {
})
__(…args) → {string}
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
any |
<repeatable> |
Returns:
| Type | Description |
|---|---|
| string |
(async) afetch(url, optionsopt)
- Description:
Promisified fetch which returns a Promise, all exceptions are passed to the reject handler, no need to use try..catch Return everything in an object
{ ok, status, err, data, info }.
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
url |
string | ||
options |
object |
<optional> |
Example
const { err, data } = await afetch("https://localhost:8000")
const { ok, err, status, data } = await afetch("https://localhost:8000")
if (!ok) console.log(status, err);
call(obj, methodopt)
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
obj |
object | function | ||
method |
string | function |
<optional> |
|
...args |
any |
<optional> |
Example
app.call(func,..)
app.call(obj, func, ...)
app.call(obj, method, ...)
emit(event, …args)
- Description:
Send an event to all listeners at once, one by one.
If the event ends with :* it means notify all listeners that match the beginning of the given pattern, for example:
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
event |
string | ||
args |
any |
<repeatable> |
Example
notify topic:event1, topic:event2, ...
app.emit("topic:*",....)
escape(str) → {string}
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string |
Returns:
| Type | Description |
|---|---|
| string |
fetch(url, optionsopt, callbackopt)
- Description:
Fetch remote content, wrapper around Fetch API
NOTE: Saves X-CSRF-Token header and sends it back with subsequent requests
- Source:
Parameters:
| Name | Type | Attributes | Description | ||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
url |
string | URL to fetch |
|||||||||||||||||||||||||||||
options |
object |
<optional> |
Properties
|
||||||||||||||||||||||||||||
callback |
function |
<optional> |
callback as (err, data, info) where info is an object { status, headers, type } |
Example
fetch("http://api.host.com/user/123", (err, data, info) => {
if (info.status == 200) console.log(data, info);
});
forEach(list, iterator, callback, direct)
- Description:
Apply an iterator function to each item in an array in parallel. Execute a callback when all items have been completed or immediately if there is an error provided.
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
list |
Array.<any> | |
iterator |
function | |
callback |
function | |
direct |
boolean | controls how the final callback is called, if true it is called directly otherwisde via setImmediate |
Example
forEach([ 1, 2, 3 ], function (i, next) {
console.log(i);
next();
}, (err) => {
console.log('done');
});
forEachSeries(list, iterator, callbackopt, directopt)
- Description:
Apply an iterator function to each item in an array serially. Execute a callback when all items have been completed or immediately if there is is an error provided.
- Source:
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
list |
Array.<any> | |||
iterator |
function | |||
callback |
function |
<optional> |
||
direct |
boolean |
<optional> |
true
|
Example
forEachSeries([ 1, 2, 3 ], function (i, next, data) {
console.log(i, data);
next(null, data);
}, (err, data) => {
console.log('done', data);
});
hideAlert(container, optionsopt)
- Description:
Hide active Bootstrap alert
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
container |
HTMLElement | ||
options |
Object |
<optional> |
hideToast()
- Description:
Hide active toasts inside first .toast-container
- Source:
isArray(val) → {any|Array.<any>}
- Description:
Returns the array if the value is non empty array or dflt value if given or undefined
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
val |
any |
Returns:
| Type | Description |
|---|---|
| any | Array.<any> |
isElement(element) → {HTMLElement|undefined}
Parameters:
| Name | Type | Description |
|---|---|---|
element |
any |
Returns:
| Type | Description |
|---|---|
| HTMLElement | undefined |
isFlag(list, item) → {boolean}
Parameters:
| Name | Type | Description |
|---|---|---|
list |
Array.<any> | |
item |
any | Array.<any> |
Returns:
| Type | Description |
|---|---|
| boolean |
true if |
isFunction(callback) → {function|undefined}
Parameters:
| Name | Type | Description |
|---|---|---|
callback |
any |
Returns:
| Type | Description |
|---|---|
| function | undefined |
isNumber(num) → {number|undefined}
Parameters:
| Name | Type | Description |
|---|---|---|
num |
any |
Returns:
| Type | Description |
|---|---|
| number | undefined |
isObject(obj) → {object|undefined}
Parameters:
| Name | Type | Description |
|---|---|---|
obj |
any |
Returns:
| Type | Description |
|---|---|
| object | undefined |
isString(str) → {string}
Parameters:
| Name | Type | Description |
|---|---|---|
str |
any |
Returns:
| Type | Description |
|---|---|
| string |
loadResources(urls, optionsopt)
- Description:
Inject CSS/Script resources into the current page, all urls are loaded at the same time by default.
- Source:
Parameters:
| Name | Type | Attributes | Description | ||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
urls |
Array.<string> | string | list of urls to load |
|||||||||||||||||||||
options |
object |
<optional> |
Properties
|
log()
noop()
off(event|namespace, callbackopt)
- Description:
Remove all event listeners for the event name and exact callback or namespace
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
event|namespace |
string |
|
|
callback |
function | string |
<optional> |
|
Example
app.on("component:*", (ev) => { ... }, "myapp")
...
app.off("myapp")
on(event, callback, namespaceopt)
- Description:
Listen on event, the callback is called synchronously, optional namespace allows deleting callbacks later easier by not providing exact function by just namespace.
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
event |
string | ||
callback |
function | ||
namespace |
string |
<optional> |
once(event, callback, namespaceopt)
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
event |
string | ||
callback |
function | ||
namespace |
string |
<optional> |
only(event, callback, namespaceopt)
- Description:
Remove all current listeners for the given event, if a callback is given make it the only listener.
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
event |
string | ||
callback |
function | ||
namespace |
string |
<optional> |
parallel(tasks, callbackopt, directopt)
- Description:
Execute a list of functions in parallel and execute a callback upon completion or occurance of an error. Each function will be passed a callback to signal completion. The callback accepts an error for the first argument. The iterator and callback will be called via setImmediate function to allow the main loop to process I/O unless the
directargument is true
- Source:
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
tasks |
Array.<function()> | |||
callback |
function |
<optional> |
||
direct |
boolean |
<optional> |
true
|
parsePath(path) → {Object}
- Description:
Parses component path and returns an object with at least { name, params } ready for rendering. External urls are ignored.
Passing an object will retun a shallow copy of it with name and params properties possibly set if not provided.
The path can be:
- component name
- relative path: name/param1/param2/param3/....
- absolute path: /app/name/param1/param2/...
- URL: https://host/app/name/param1/...
All parts from the path and query parameters will be placed in the params object.
The .html extention will be stripped to support extrernal loading but other exts will be kept as is.
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
path |
string | object |
Returns:
| Type | Description |
|---|---|
| Object |
in format { name, params } |
register(name, options, render, cleanup, data)
- Description:
Register a render plugin, at least 2 functions must be defined in the options object:
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
name |
string | ||
options |
object | ||
render |
function | (element, options) to show a component, called by render |
|
cleanup |
function | (element) - optional, run additional cleanups before destroying a component |
|
data |
function | (element) - return the component class instance for the given element or the main |
|
options.default |
boolean |
<optional> |
if not empty make this plugin default |
options.Component |
class |
<optional> |
optional base component constructor, it will be registered as app.{Type}Component, like AlpineComponent, KoComponent,... to easy create custom components in CDN mode The reason for plugins is that while this is designed for Alpine.js, the idea originated by using Knockout.js with this system, the plugin can be found at app.ko.js. There is a simple plugin in examples/simple.js to show how to use it without any rendering engine with vanillla HTML, not very useful though. |
render(options, dfltopt) → {object|undefined}
- Description:
Show a component, options can be a string to be parsed by parsePath or an object with { name, params } properties. if no params.$target provided a component will be shown inside the main element defined by $target.
It returns the resolved component as described in resolve method after rendering or nothing if nothing was shown.
When showing main app the current component is asked to be deleted first by sending an event prepare:delete, a component that is not ready to be deleted yet must set the property event.stop in the event handler onPrepareDelete(event) in order to prevent rendering new component.
To explicitly disable history pass options.$nohistory or params.$nohistory otherwise main components are saved automatically by sending the path:save event.
A component can globally disable history by creating a static property $nohistory in the class definition.
To disable history all together set
app.$nohistory = true.
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
options |
string | object | ||
dflt |
string |
<optional> |
Returns:
| Type | Description |
|---|---|
| object | undefined |
resolve(path, dfltopt) → {object}
- Description:
Returns an object with template and component properties.
Calls parsePath first to resolve component name and params.
Passing an object with 'template' set will reuse it, for case when template is already resolved.
The template property is set as:
- try app.templates[.name]
- try an element with ID name and use innerHTML
- if not found and dflt is given try the same with it
- if template texts starts with # it means it is a reference to another element's innerHTML, otemplate is set with the original template before replacing the template property
- if template text starts with $ it means it is a reference to another template in app.templates, otemplate is set with the original template before replacing the template property
The component property is set as:
- try app.components[.name]
- try app.components[dflt]
- if resolved to a function return
- if resolved to a string it refers to another component, try app.templates[component], ocomponent is set with the original component string before replacing the component property
if the component property is empty then this component is HTML template.
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
path |
string | ||
dflt |
string |
<optional> |
Returns:
| Type | Description |
|---|---|
| object |
in format { name, params, template, component } |
restorePath(path)
- Description:
Show a component by path, it is called on path:restore event by default from start and is used to show first component on initial page load. If the path is not recognized or no component is found then the default index component is shown.
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
path |
string |
sanitizer(html, list) → {Array.<Node>|string}
Parameters:
| Name | Type | Description |
|---|---|---|
html |
strings | |
list |
boolean | if true return a list of Nodes |
Returns:
| Type | Description |
|---|---|
| Array.<Node> | string |
savePath(options)
- Description:
Saves the given component in the history as ** /name/param1/param2/param3/.. **
It is called on every component:create event for main components as a microtask, meaning immediate callbacks have a chance to modify the behaviour.
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
options |
Object |
sendFile(url, options, callbackopt)
Parameters:
| Name | Type | Attributes | Description | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
url |
string | ||||||||||||||||||
options |
object |
Properties
|
|||||||||||||||||
callback |
function |
<optional> |
series(tasks, callbackopt, directopt)
- Description:
Execute a list of functions serially and execute a callback upon completion or occurance of an error. Each function will be passed a callback to signal completion. The callback accepts either an error for the first argument in which case the flow will be aborted and the final callback will be called immediately or some optional data to be passed to thr next iterator function as a second argument.
The iterator and callback will be called via setImmediate function to allow the main loop to process I/O unless the
directargument is true
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
tasks |
Array.<function()> | ||
callback |
function |
<optional> |
|
direct |
boolean |
<optional> |
Example
series([
function(next) {
next(null, "data");
},
function(next, data) {
setTimeout(function () { next(null, data); }, 100);
},
], (err, data) => {
console.log(err, data);
});
showAlert(containeropt, type, text, optionsopt)
- Description:
Show Bootstrap alert
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
container |
HTMLElement |
<optional> |
show inside container or document.body |
type |
string | type of alert: error, danger, warning, info, success, primary |
|
text |
string | text to show |
|
options |
Object |
<optional> |
showToast(containeropt, type, text, optionsopt)
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
container |
HTMLElement |
<optional> |
show inside container or document.body |
type |
string | type of alert: error, danger, warning, info, success, primary |
|
text |
string | text to show |
|
options |
Object |
<optional> |
split(str, sepopt, optionsopt) → {Array.<string>}
Parameters:
| Name | Type | Attributes | Default | Description | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
str |
string | If str is an array and type is not specified then all non-string items will be returned as is. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
sep |
RegExp | string |
<optional> |
,|
|
separator |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
options |
object |
<optional> |
Properties
|
Returns:
| Type | Description |
|---|---|
| Array.<string> |
start()
- Description:
Setup default handlers:
- on path:restore event call restorePath to render a component from the history
- on path:save call savePath to save the current component in the history
- on page ready call restorePath to render the initial page
If not called then no browser history will not be handled, up to the app to do it some other way.. One good reason is to create your own handlers to build different path and then save/restore.
- Source:
stylePlugin(callback)
- Description:
Add a callback to process classes for new components, all registered callbacks will be called on component:create event with top HTMLElement as parameter. This is for UI frameworks intergation to apply logic to added elements
- Source:
Parameters:
| Name | Type | Description |
|---|---|---|
callback |
function |
Example
app.stylePlugin((el) => {
app.$all(".carousel", element).forEach(el => (bootstrap.Carousel.getOrCreateInstance(el)));
})
toCamel(str) → {string}
Parameters:
| Name | Type | Description |
|---|---|---|
str |
string |
Returns:
| Type | Description |
|---|---|
| string |
toDate(val, dfltopt, invalidopt) → {Date}
- Description:
Return Date object for given text or numeric date representation, for invalid date returns 1969 unless
invalidparameter is given, in this case invalid date returned as null. Ifdfltis NaN, null or 0 returns null as well.
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
val |
string | Date | number | ||
dflt |
any |
<optional> |
|
invalid |
boolean |
<optional> |
Returns:
| Type | Description |
|---|---|
| Date |
toDuration(mtime, ageopt) → {string}
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
mtime |
number | ||
age |
boolean |
<optional> |
if true duration from now, as age |
Returns:
| Type | Description |
|---|---|
| string |
toNumber(val, optionsopt) → {number}
- Description:
Safe convertion to a number, no expections, uses 0 instead of NaN, handle booleans, if float specified, returns as float.
- Source:
Parameters:
| Name | Type | Attributes | Description | ||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
val |
any | to be converted to a number |
|||||||||||||||||||||||||||||||||||||||||||||
options |
object |
<optional> |
Properties
|
Returns:
| Type | Description |
|---|---|
| number |
Example
toNumber("123")
123
toNumber("1.23", { float: 1, dflt: 0, min: 0, max: 2 })
1.23
toPrice(num, optionsopt)
- Description:
Return a test representation of a number according to the money formatting rules,
- Source:
Parameters:
| Name | Type | Attributes | Description | |||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
num |
number | |||||||||||||||||||||||||||||||||||||
options |
object |
<optional> |
Properties
|
toSize(size, decimalsopt)
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
size |
number | |||
decimals |
boolean |
<optional> |
2
|
toTitle(name, minlenopt) → {string}
- Description:
Convert text into capitalized words, if it is less or equal than minlen leave it as is
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
name |
string | ||
minlen |
int |
<optional> |
Returns:
| Type | Description |
|---|---|
| string |
trace(…args)
- Description:
if app.debug is set then it will log arguments in the console otherwise it is no-op
- Source:
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
args |
any |
<repeatable> |