Global

Type Definitions

BootpopupElement

Description:
  • Configuration object for a single element in a Bootpopup form/layout.

    “Special element properties” are parsed by Bootpopup to create DOM, apply Bootstrap classes, add labels/groups, input-group addons, validation feedback, etc.

Source:
Properties:
Name Type Attributes Description
class string <optional>

Classes for the main element. If empty/omitted, form-control is used.

text string <optional>

Sets element's textContent.

html string <optional>

HTML to be parsed into DOM and appended (after sanitizing, if available).

autofocus boolean <optional>

Focus this element when the popup is shown.

nosanitize boolean <optional>

Skip sanitizer for label or html (if sanitizer is installed).

floating boolean <optional>

Adds form-floating to the group to enable floating labels.

checked boolean <optional>

When true, makes checkbox/radio selected.

switch boolean <optional>

When true, converts a checkbox into a toggle switch style.

inline boolean <optional>

When true, adds form-check-inline (checkbox/radio inline style).

reverse boolean <optional>

When true, adds form-check-reverse (checkbox style).

input_label string <optional>

Checkbox/radio specific label instead of the element's main label.

class_input_btn string <optional>

Converts checkbox into a button style. Must be one of Bootstrap btn-* classes.

class_check string <optional>

Adds a custom class to the checkbox/radio input element.

class_label string <optional>

Extra classes for the label element (added to default form-label).

attrs_label Object.<string, any> <optional>

Attributes for the label element.

size_label number | string <optional>

Column width for the label (Bootstrap grid sizing).

size_input number | string <optional>

Column width for the input (Bootstrap grid sizing).

class_group string <optional>

Classes for the group wrapper div. Example: "row my-3 py-1 border-bottom".

attrs_group Object.<string, any> <optional>

Attributes for the group wrapper div. Example: { id: "group1" }.

class_prefix string <optional>

Class for a prefix span inserted as the first element in the group.

text_prefix string <optional>

Text for a prefix span inserted as the first element in the group.

class_suffix string <optional>

Class for a suffix element inserted as the last element in the group.

text_suffix string <optional>

Text for a suffix element inserted as the last element in the group.

text_valid string <optional>

Adds a “valid feedback” div (used with validate()).

text_invalid string <optional>

Adds an “invalid feedback” div (used with validate()).

class_append string <optional>

Appends a span to the element (mostly for non-input entries) with this class.

text_append string <optional>

Appends a span to the element (mostly for non-input entries) with this text.

text_input_button string <optional>

Adds a button tied to the input to perform an action. The button gets data-formid and data-inputid attributes.

class_input_button string <optional>

Button style class for the input button.

class_input_group string <optional>

Class for the input-group wrapper when using input buttons / dropdowns.

attrs_input_button Object.<string, any> <optional>

Attributes for the input button (often includes { click: (ev) => {} }).

list_input_button Array.<(string|{name:string, value:any})> <optional>

Adds a dropdown button with options; selected value is placed into an input.

list_input_tags Array.<(string|{name:string, value:any})> <optional>

Same as list_input_button, but also adds selected values as tags in the list.

class_list_button string <optional>

Class for the dropdown list button.

class_input_menu string <optional>

Class for the dropdown menu.

Type:
  • Object

BootpopupOptions

Description:
  • Bootpopup creation options.

Source:
Properties:
Name Type Attributes Default Description
content Array.<BootpopupElement> <optional>
[]

Content of the dialog box.

footer Array.<BootpopupElement> <optional>
[]

Content inside the modal footer (simple elements only).

title string <optional>
document.title

Title of the dialog box.

show_close boolean <optional>
true

Show or hide the close button in the title.

show_header boolean <optional>
true

Show or hide the dialog header with title.

show_footer boolean <optional>
true

Show or hide the dialog footer with buttons.

keyboard boolean <optional>
true

If false, disable closing the modal with keyboard.

backdrop boolean | string <optional>
true

If false, disable modal backdrop; can be static as well.

scroll boolean <optional>
true

Apply modal-dialog-scrollable if true.

center boolean <optional>
false

Apply modal-dialog-centered if true.

horizontal boolean <optional>
false

Enable/disable horizontal layout in the form element.

size "sm" | "lg" | "xl" | "" <optional>
""

Size of the modal window.

size_label string <optional>
"col-sm-4"

Classes applied to labels in the form.

size_input string <optional>
"col-sm-8"

Classes applied to inputs wrapper in the form.

onsubmit "close" | "ok" | "cancel" | "yes" | "no" <optional>
"close"

Default action when form is submitted (overridden by submit callback).

buttons Array.<("close"|"ok"|"cancel"|"yes"|"no")> <optional>
["close"]

Buttons shown in the dialog footer.

before function <optional>
function(){}

Called before the window is shown, after being created. (popup).

dismiss function <optional>
function(){}

Called when the window is dismissed. (data).

submit function <optional>
function(){}

Called when the form is submitted. Return false to cancel. (data).

close function <optional>
function(){}

Called when Close button is selected. (data).

ok function <optional>
function(){}

Called when OK button is selected. (data).

cancel function <optional>
function(){}

Called when Cancel button is selected. (data).

yes function <optional>
function(){}

Called when Yes button is selected. (data).

no function <optional>
function(){}

Called when No button is selected. (data).

complete function <optional>
function(){}

Always called when the dialog box has completed. (data).

alert boolean <optional>
false

If true, adds an alert element to be shown by showAlert.

info boolean <optional>
false

If true, adds an info element to be shown by showAlert(..., {type:"info"}).

autofocus boolean <optional>
true

If true, focus the first input element when shown.

empty boolean <optional>
false

If true, return all input values even if empty; default returns only non-empty values.

sanitizer function <optional>
null

Called when rendering HTML content/labels; must return a list of HTMLElements to append.

tabs Object.<string, string> | null <optional>
null

Map of {tabId: label, ...} to show nav-tabs; content items can set tab_id.

self Object <optional>

Context for callback functions; default is the popup object.

debug boolean <optional>
false

Log input values in the console.

class_modal string <optional>
"modal fade"

Modal root class.

class_dialog string <optional>
"modal-dialog"

Modal dialog class.

class_title string <optional>
"modal-title"

Modal title class.

class_content string <optional>
"modal-content"

Modal content class.

class_body string <optional>
"modal-body"

Modal body class.

class_header string <optional>
"modal-header"

Modal header class.

class_footer string <optional>
"modal-footer"

Modal footer class.

class_options string <optional>
"options flex-grow-1 text-start"

Wrapper class for footer content.

class_alert string <optional>
"alert alert-danger fade show"

Class for danger alerts shown by showAlert.

class_info string <optional>
"alert alert-info fade show"

Class for info alerts shown by showAlert.

class_form string <optional>
""

Class for the form wrapper div.

class_buttons string <optional>
"btn"

Base class for all buttons.

class_button string <optional>
"btn-outline-secondary"

Default style class for buttons (appended to class_buttons).

class_ok string <optional>
"btn-primary"

Style class for OK button.

class_yes string <optional>
"btn-primary"

Style class for Yes button.

class_no string <optional>
"btn-secondary"

Style class for No button.

class_cancel string <optional>
"btn-outline-secondary"

Style class for Cancel button.

class_close string <optional>
"btn-outline-secondary"

Style class for Close button.

class_tabs string <optional>
"nav nav-tabs mb-4"

Class for tab nav.

class_tablink string <optional>
"nav-link"

Class for tab links.

class_tabcontent string <optional>
"tab-content"

Class for tab content container.

class_group string <optional>
"row mb-3"

Wrapper class for each content element group.

class_label string <optional>
""

Extra class appended to form labels.

class_row string <optional>
"row"

Class used for content type row.

class_col string <optional>
"col-auto"

Class used for columns in row content items.

class_suffix string <optional>
"form-text text-muted text-end"

Class used for content added to a group (suffix/help text).

class_input_button string <optional>
"btn btn-outline-secondary"

Default class for text_input_button.

class_list_button string <optional>
"btn btn-outline-secondary dropdown-toggle"

Default class for list_input_button button.

class_input_menu string <optional>
"dropdown-menu bg-light"

Default class for list_input_button dropdown.

list_input_mh string <optional>
"25vh"

Default max height of the dropdown in list_input_button.

Type:
  • Object

Members

fetchOptions

Description:
  • Global object to customize fetch

Source:
Example

make POST default method

fetchOptions.method = "POST"
await fetch("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>}

Description:
  • An alias for document.querySelectorAll

Source:
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}

Description:
  • Return or set attribute by name from the given element.

Source:
Parameters:
Name Type Attributes Description
element HTMLElement | string
attr string
value any <optional>
  • undefined - return the attribute value
  • null - remove attribute
  • any - assign new value
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)

Description:
  • An alias for element.removeEventListener

Source:
Parameters:
Name Type Attributes Description
element HTMLElement
event string
callback function
...args any <optional>

additional params to removeEventListener

$on(element, event, callback)

Description:
  • An alias for element.addEventListener

Source:
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)

Description:
  • A shortcut to DOMParser, default is to return the .body.

Source:
Parameters:
Name Type Attributes Description
html string
format string <optional>

defines the result format:

  • list - the result will be an array with all body child nodes, i.e. simpler to feed it to Element.append()
  • doc - return the whole parsed document
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}

Description:
  • Empty locale translator

Source:
Parameters:
Name Type Attributes Description
args any <repeatable>
Returns:
Type Description
string

bootpopup() → {Bootpopup}

Description:
  • Create an instance of Bootpoup class and show it

Source:
Parameters:
Name Type Description
...args BootpopupOptions
Returns:
Type Description
Bootpopup

DOM elements

All the following Bootpopup properties are native HTML elements:

  • modal - entire window, including the fade background. You can use this property in the same way as described in Bootstrap Modals Usage
  • dialog - entire window, without the background
  • content - content of the dialog
  • header - header of the dialog
  • body - body of the dialog
  • form - main form in the dialog, inside the body
  • footer - footer of the dialog

Buttons

  • btn_close - close button (if present)
  • btn_ok - OK button (if present)
  • btn_cancel - cancel button (if present)
  • btn_yes - yes button (if present)
  • btn_no - no button (if present)

Any ad-hoc button will be added in the form btn_Label.

NOTE: All actions by default close the popup window, a callback must return null in order to keep the popup window visible, this is useful when validating the input. Manually closing the popup is done via the close method.

About the buttons option:

In addition to default buttons ok, close, cancel, yes, no a button can be defined in ad-hoc manner with any label as long as the button callback is named the same, for example

     bootpopup({
       ...
       buttons: ["cancel", "Order"],
       Order: (data) => {
           ...
       }
     }

Clicking on the Order button will call the Order callback.

Customizing default button labels can be done via text_NAME properties, for example

bootpopup({
  buttons:["ok","cancel"],
  text_ok: "Submit",
})

Now ok will be shown as Submit. With ad-hoc labeling this is not very useful but still can be used for default buttons.

About the content option:

The biggest flexibility of Bootpopup is the content option. The content is wrapped by a form allowing to create complex forms very quickly.

When you are submitting data via a dialog box, Bootpopup will grab all that data and deliver to you through the callbacks. content is an array of objects and each object is represented as an entry of the form. For example, if you have the following object:

{ p: {class: "bold", text: "Insert data:"}}

This will add a <p></p> tag to the form. The options of p ({class: "bold", text: "Insert data:"}) are HTML attributes passed to the HTML tag. There is a special attribute for text which is defined as the inner text of the HTML tag. So, this example is equivalent to the following HTML:

<p class="bold">Insert data:</p>

But it is when it comes to adding inputs that things become easy. Look at this example:

{ input: {type: "text", label: "Title", name: "title", placeholder: "Description" }}

This will create an input element with the attributes type: "text", label: "Title", name: "title", placeholder: "Description". Note there is also a special attribute label. This attribute is used by Bootpopup to create a label for the input form entry. The above example is equivalent to the following HTML:

<div class="form-group mb-3">
  <label for="title" class="col-form-label col-sm-4">Title</label>
  <div class="col-sm-10">
    <input label="Title" name="title" id="title" placeholder="Description" class="form-control" type="text">
  </div>
</div>

In order to make it even simpler, there are shortcuts for most common input types:

"text", "color", "url", "password", "hidden", "file", "number", "email", "reset", "date", "time", "checkbox", "radio", "datetime-local", "week", "tel", "search", "range", "month", "image", "button". The previous example can be simply written as:

{ text: {label: "Title", name: "title", placeholder: "Description" }}

select, checkboxes and radios have a special attribute named options. You can specify a list of options to be shown in 2 formats:

 - an object where the key is used as value by the input and the value is the text displayed
 - a list of objects with { label:, value:, name: } properties
{ select: { label: "Select", name: "select", options: { a:"A", b:"B", c:"C" }}}
{ radios: { label: "Radios", name: "radios", options: { a:"A", b:"B", c:"C" }}}
{ checkboxes: { label: "Checkboxes", options: [ { name: "c1", label: "A" }, { name: "c2", label: "C", value: 2 } ]}}

select with attribute multiple is also supported. For multi-select to make an item selected the value must match or property selected must be true in case of objects: { name: .., value:.., selected: true }

Another useful feature is the ability to support functions directly as an attribute. Take the following button example:

{ button: {name: "button", value: "Open image", class: "btn btn-info", click: (event) => {
    console.log(event);
    bootpopup.alert("Hi there");
}}}

This will create a onclick event for the button. The reference for the object is passed as argument to the function.

You can also insert HTML strings directly. Instead of writing an JS object, write the HTML:

'<p class="lead">Popup dialog boxes for Bootstrap.</p>'

List of special element properties:

  • class - to customize the style of the element just provide all classes in the class property, if empty form-control is set
  • text - set element's textContent
  • html - parse and add DOM elements after running thru sanitizer
  • autofocus - make this element focused on show
  • nosanitize - skip sanitizer for labels or html property if installed
  • floating - add form-floating to the group to make labels floating
  • checked - true to make checkbox/radios selected
  • switch - true to convert a checkbox into a toggle style
  • inline - true to add form-check-inline to a checkbox style
  • reverse - true to add form-check-reverse to checkbox style
  • input_label - checkbox/radio specific label instead of the element's label
  • class_input_btn - convert checkbox into a button style, must be one of btn- classes
  • class_check - add custom class to checkbox/radio element
  • class_label - to customize the label style, added to the default form-label
  • attrs_label - attributes for the label element, an object
  • size_label - set column width for the label
  • size_input - set column width for the input
  • class_group - to customize the group, example: { class_group: "row my-3 py-1 border-bottom" } to set border and gaps for an element
  • attrs_group - attributes for the group div, an object, example: { attrs_group: { id: "group1" } }
  • class_prefix and/or text_prefix - add as a first span to the group with a span with class/text
  • class_suffix and/or text_suffix - make it the last div in the group with class/text
  • text_valid, text_invalid - add divs for valid or invalid feedback, to be used with validate method
  • class_append and/or text_append - append a span to an element, mostly for non-input entries
  • text_input_button - add a button the element to perform an action on it, data-formid and data-inputid are set on the button with form and the input elem ent ids for easy access in the callbacks, use class_input_button to change the button style, use class_input_group to change the input group style
  • attrs_input_button - attributes to the input button, an object, usually { click: (ev) => {} }
  • list_input_button or list_input_tags - add a dropdown button with options to select and place into an input, use class_list_button to change the button style, use class_input_group to change the input group style, use class_input_menu to change the dropdown menu style, the list can be an Array of strings or ob jects { name:, value: }. The list_input_tags adds a selected value in the list.

Alert:

bootpopup.alert("Hi there");

Confirm:

bootpopup.confirm("Do you confirm this message?", (yes) => {
  alert(yes);
});

Prompt:

bootpopup.prompt("Name", (value) => {
  alert(value);
});

Customized prompt:

bootpopup({
   title: "Add image",
    content: [
        '<p class="lead">Add an image</p>',
        { p: {text: "Insert image info here:"}},
        { input: {type: "text", label: "Title", name: "title", placeholder: "Description for image"}},
        { input: {type: "text", label: "Link", name: "link", placeholder: "Hyperlink for image"}}],
    buttons: ["ok", "cancel"],
    cancel: () => { alert("Cancel") },
    ok: (data, list) => { console.log(data, list) },
    complete: () => { alert("complete") },
});

### Validation:

```javascript
var popup = bootpopup({
  title: "Add details",
  alert: 1,
  content: [
      { text: { label: "Name", name: "title", placeholder: "your name"}},
      { number: { label: "Age", name: "age", placeholder: "your age"}}],
  buttons: ["ok", "cancel"],
  text_ok: "Verify",
  ok: (data) => {
      if (!data.name) return popup.showAlert("name is required")
  },
});

See more Examples.

call(obj, methodopt)

Description:
  • Call a function safely with context and arguments:

Source:
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}

Description:
  • Convert common special symbols into xml entities

Source:
Parameters:
Name Type Description
str string
Returns:
Type Description
string

(async) 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
Name Type Attributes Description
method string <optional>

GET, POST,...GET is default or from app.fetchOptions.method

post boolean <optional>

set method to POST

body string | object | FormData <optional>

a body accepted by window.fetch

dataType string <optional>

explicit return type: text, blob, default is auto detected between text or json

headers object <optional>

an object with additional headers to send, all global headers from app.fetchOptions.headers also are merged

request object <optional>

properties to pass to fetch options according to Web API RequestInit

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);
});

const { err, data } = await fetch("https://localhost:8000")

const { ok, err, status, data } = await fetch("https://localhost:8000")
if (!ok) console.log(status, err);

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}

Description:
  • Returns the element itself if it is a HTMLElement

Source:
Parameters:
Name Type Description
element any
Returns:
Type Description
HTMLElement | undefined

isFlag(list, item) → {boolean}

Source:
Parameters:
Name Type Description
list Array.<any>
item any | Array.<any>
Returns:
Type Description
boolean

true if item exists in the array list, search is case sensitive. if item is an array it will return true if any element in the array exists in the list.

isFunction(callback) → {function|undefined}

Description:
  • Returns the callback is it is a function

Source:
Parameters:
Name Type Description
callback any
Returns:
Type Description
function | undefined

isNumber(num) → {number|undefined}

Description:
  • Returns the num itself if it is a number

Source:
Parameters:
Name Type Description
num any
Returns:
Type Description
number | undefined

isObject(obj) → {object|undefined}

Description:
  • Returns the obj itself if it is a not null object

Source:
Parameters:
Name Type Description
obj any
Returns:
Type Description
object | undefined

isString(str) → {string}

Description:
  • Returns the str itself if it is not empty or ""

Source:
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
Name Type Attributes Description
series boolean <optional>

load urls one after another

callback function <optional>

will be called with (el, opts) args for customizations after loading each url or on error

attrs object <optional>

is an object with attributes to set like nonce, ...

timeout int <optional>

call the callback after timeout

log()

Description:
  • Alias to console.log

Source:

noop()

Description:
  • Empty function

Source:

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
  • event name if callback is not empty
  • namespace if no callback
callback function | string <optional>
  • function - exact callback to remove for the event
  • string - namespace for the event
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)

Description:
  • Listen on event, the callback is called only once

Source:
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 direct argument 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}

Description:
  • HTML sanitizer, based on Bootstrap internal sanitizer

Source:
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

(async) sendFile(url, options, callbackopt)

Description:
  • Send file(s) and forms, a wrapper around fetch

Source:
Parameters:
Name Type Attributes Description
url string
options object
Properties
Name Type Attributes Description
files object <optional>

name/File pairs to be sent as multi-part

body object <optional>

simple form properties

json object <optional>

send as JSON blobs

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 direct argument 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>}

Description:
  • Split string into array, ignore empty items by default

Source:
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
Name Type Attributes Description
keepempty boolean <optional>

will preserve empty items, by default empty strings are ignored

notrim boolean <optional>

will skip trimming strings, trim is the default

max int <optional>

will skip strings over the specificed size if no trunc

trunc boolean <optional>

will truncate strings longer than max

regexp regexp <optional>

will skip string if not matching

noregexp regexp <optional>

will skip string if matching

number boolean <optional>

convert into a number

cap boolean <optional>

capitalize

camel boolean <optional>

camelize

lower boolean <optional>

lowercase

upper boolean <optional>

uppercase

strip string | regexp <optional>

remove occurences

replace object <optional>

an object map which characters to replace with new values

range boolean <optional>

will parse numeric ranges in the format NUM-NUM and add all numbers in between, invalid ranges are skipped

unique boolean <optional>

remove duplicate entries

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}

Description:
  • Convert a string into camelized format

Source:
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 invalid parameter is given, in this case invalid date returned as null. If dflt is 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}

Description:
  • Return duration in human format, mtime is msecs

Source:
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
Name Type Attributes Default Description
dflt int <optional>

default value

float int <optional>

treat as floating number

min int <optional>

minimal value, clip

max int <optional>

maximum value, clip

incr int <optional>

a number to add before checking for other conditions

mult int <optional>

a number to multiply before checking for other conditions

novalue int <optional>

replace this number with default

zero int <optional>

replace with this number if result is 0

digits int <optional>

how many digits to keep after the floating point

bigint int <optional>

return BigInt if not a safe integer

base int <optional>
10

base of the input, 2, 10, 16, ...

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
Name Type Attributes Default Description
locale string <optional>
en-US
currency string <optional>
USD
display string <optional>
symbol
sign string <optional>
standard
min int <optional>
2
max int <optional>
3

toSize(size, decimalsopt)

Description:
  • Return size human readable format

Source:
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>