Script

Callbacks

Options for callback functions

Functions passed in as parameters to any Wee API method are evaluated in the same fashion. Usually, an options object will be provided for these Wee API methods that take a callback function that can have the following properties:

VariableTypeDefaultDescriptionRequired

args

array

-

Arguments to be passed into value if value is function

scope

object

-

Scope assigned to value if value is a function

$assets.load

Load assets with specified set of options

VariableTypeDefaultDescriptionRequired

options

object

-

Object parameters below

Configuration Object

VariableTypeDefaultDescriptionRequired

async

boolean

true

Loads assets asynchronously, only applicable to scripts

cache

boolean

true

Bust request cache with random querystring

styles

string, array

-

Single CSS path or array of CSS paths

error

function

-

Failure callback

files

string, array

-

Single file path or array of file paths

group

string

-

Optional reference for use with ready

images

string, array

-

Single image path or array of image paths

scripts

string, array

-

Single JavaScript path or array of JavaScript paths

root

string

-

Root path or domain override for root

success

function

-

Success callback

Single File

import $assets from 'wee-assets';

$assets.load({
    files: '/path/to/alert.js',
    success() {
        // Success logic
    },
    error() {
        // Failure logic
    }
});

Multiple Files

import $assets from 'wee-assets';

$assets.load({
    root: 'https://cdn.weepower.com',
    files: [
        '/path/to/alert.js',
        '/path/to/override.css',
        '/path/to/sample.png'
    ],
    success() {
        // Success logic
    },
    error() {
        // Failure logic
    }
});

If an absolute URL beginning with "//", "http://", or “https://” is requested the root option will be ignored.

Group

import $assets from 'wee-assets';

$assets.load({
    files: '/path/to/alert.js',
    group: 'dynamicAssets'
});

$assets.ready('dynamicAssets', {
    success() {
        // Success logic
    },
    error() {
        // Failure logic
    }
});

$assets.ready

When specified references are ready execute callback

VariableTypeDefaultDescriptionRequired

group

string

-

Group reference name

options

object

-

Override any load configuration options

poll

boolean

false

Poll the queue every 20 milliseconds for completion

Check

import $assets from 'wee-assets';

$assets.ready('dynamicAssets');
true

Check and Set

import $assets from 'wee-assets';

$assets.ready('dynamicAssets', {
    success() {
        // Success logic
    }
});

$assets.remove

Remove one or more files from the DOM

VariableTypeDefaultDescriptionRequired

files

string, array

-

Single file path or file array

root

string

-

Root path or domain override for root

Single File

import $assets from 'wee-assets';

$assets.remove('/samples/override.css');

Multiple Files

import $assets from 'wee-assets';

$assets.remove([
    '/samples/override.css',
    '/samples/alert.js'
], 'https://cdn.weepower.com');

$assets.root

Get current asset root or set with specified value

VariableTypeDefaultDescriptionRequired

value

string

-

Root request path

Set

The value set here is prepended to every request if not specifically overridden.

import $assets from 'wee-assets';

$assets.root('https://cdn.weepower.com');

Get

Retrieve the current root which defaults to an empty string, unless previously set.

import $assets from 'wee-assets';

$assets.root();
"https://cdn.weepower.com"

Advanced

Only set the asset root to a CDN in the production environment.

import { $env } from 'core/core';
import $assets from 'wee-assets';

if ($env() == 'prod') {
    $assets.root('https://cdn.weepower.com');
}

You can override the root on individual requests. For instance, you may want to load all your static assets from a CDN but pull JSON or other files from a local server.

Response

Response object returned by all requests

Properties

VariableTypeDefaultDescriptionRequired

config

object

-

Request configuration

data

object, string

-

Response data

headers

object

-

Parse response headers

request

object

-

XHR request object

status

number

-

Response status code

statusText

string

-

Response status text

$el.map

Translate items in selection into new array

VariableTypeDefaultDescriptionRequired

fn

function

-

Callback function

options

object

-

See options for $map

<div class='js-selection'>Hello</div>
<div class='js-selection'>World</div>
import $ from 'wee-dom';

$('.js-selection').map((el) => {
    return el.textContent;
});
['Hello', 'World']

$el.each

Execute function for each element in selection

VariableTypeDefaultDescriptionRequired

fn

function

-

Callback function

options

object

-

See options for $each

import $ from 'wee-dom';

$('.js-element').each((el, i) => {
    // Callback logic
});

$el.toArray

Cast selection to array

import $ from 'wee-dom';

$('.js-elements').toArray();

$el.reverse

Reverse order of selection results

import $ from 'wee-dom';

$('.js-element').reverse();

$

Get matches to specified selector or return parsed HTML

VariableTypeDefaultDescriptionRequired

selector

selection

-

Target selection or HTML string

context

selection

document

Context selection

Simple

import $ from 'wee-dom';

$('.js-element li');
[node, node, ...]

Contextual

The context selection subsets the query to a more specific scope. This can result in a more limited and efficient traversal of the DOM.

import $ from 'wee-dom';

$('li', '.js-element');
[node, node, ...]

Selection of DOM elements

Wee accepts any browser-supported selection queries. Internally Wee parses the selection string to invoke the most efficient native selection method and returns an array of matching nodes.

Examples

$('#id');
$('.class');
$('#id .class');
$('.class1, .class2');
$('.parent > .child');

data-ref

References are a logical approach to selecting elements. They are cached when the page loads making them extremely quick to reference and are more visually distinct in markup than js- classes. Anywhere you can pass a standard selector you can also pass a ‘ref:name’ string.

<div data-ref="element"></div>
$('ref:element');

// Shorthand
$(':element');

References can’t be used in subset selectors like $('ref:element .child'). To scope a selection within a reference pass the ref selector as the context argument like $('.child', 'ref:element').

If multiple references are set with the same name they are pushed into an array and can be targeted with a single ref selection. You can also provide a comma-delimited list of multiple refs.

<div data-ref="element"></div>
<div data-ref="element element2"></div>
$('ref:element');

$('ref:element, ref:element2');

$el.addClass

Add classes to each matching selection

VariableTypeDefaultDescriptionRequired

value

function, string

-

Class name(s) to add or callback

Single

import $ from 'wee-dom';

$('ref:element').addClass('modifier');

Multiple

Separate multiple class names with spaces.

import $ from 'wee-dom';

$('ref:element').addClass('modifier modifier2');

Function

The current index and class value are injected into the callback. The scope of this is the element.

import $ from 'wee-dom';

$('ref:element').addClass(function(i, className) {
    // Add an indexed class
    return className + i;
});

The index argument is always 0-based.

$el.after

Insert selection or markup after each matching selection

VariableTypeDefaultDescriptionRequired

source

function, selection, string

-

Source selection, callback, or HTML string

remove

boolean

false

Remove target after insertion

Selection

import $ from 'wee-dom';

$('ref:element').after($('.js-element'));

Markup

import $ from 'wee-dom';

$('ref:element').after('<span>Injected notice</span>);

Function

The current index and HTML are injected into the callback. The scope of this is the element.

<div data-name="John Smith">
    <h1 data-ref="bioName">Name</h1>
</div>
import $ from 'wee-dom';

$(ref.bioName').after(function(i, html) {
    // Add the parent data-name as a paragraph after the matched element
    return '<p>' + $data.(this).parent('name') + '</p>;
});
<div data-name="John Smith">
    <h1 data-ref="bioName">Name</h1>
    <p>John Smith</p>
</div>

$el.append

Append selection or markup after each matching selection

VariableTypeDefaultDescriptionRequired

source

function, selection, string

Source selection, callback, or HTML string

Selection

import $ from 'wee-dom';

$('ref:element').append($('.js-element'));

Function

The current index and HTML are injected into the callback. The scope of this is the element.

<h1 data-ref="listHeading">Names</h1>
<ul>
    <li>John Doe</li>
    <li>Jane Doe</li>
</ul>
import $ from 'wee-dom';

$('ref:listHeading').append(function(i, html){
    // Modify the heading to include the number of listed names
    return ' (' + $children($next()).length + ')';
});
<h1 data-ref="listHeading">Names (2)</h1>
<ul>
    <li>John Doe</li>
    <li>Jane Doe</li>
</ul>

$el.attr

Get attribute of first matching selection or set attribute of each matching selection

VariableTypeDefaultDescriptionRequired

attribute

string, object

-

Attribute to get or set or an object

value

function, string

-

Value to assign to attribute

Get

import $ from 'wee-dom';

$('ref:element').attr('href');
"https://www.weepower.com"

Single

import $ from 'wee-dom';

$('ref:element').attr('href', 'https://www.weepower.com/start');

Multiple

import $ from 'wee-dom';

$('ref:element').attr({
    href: 'https://developer.mozilla.org',
    target: '_blank'
});

$el.before

Insert selection or markup before each matching selection

VariableTypeDefaultDescriptionRequired

source

function, selection, string

-

Source selection, callback or HTML string

remove

boolean

false

Remove target after insertion

Selection

import $ from 'wee-dom';

$('ref:element').before($('.js-element'));

Markup

import $ from 'wee-dom';

$('ref:element').before('<span>Injected notice</span>');

Function

import $ from 'wee-dom';

$('ref:element').before(function(i, html) {
    //Callback logic
});

$el.children

Get unique direct children of each matching selection

VariableTypeDefaultDescriptionRequired

filter

selection

-

Filter selection

All Children

Without a filter all direct children will be returned.

import $ from 'wee-dom';

$('ref:element').children();

Filtered

With a filter, only matching children will be returned.

import $ from 'wee-dom';

$('ref:element').children('li');

The response excludes text and comment nodes.

$el.clone

Clone each matching selection

import $ from 'wee-dom';

$('ref.element').clone();

$el.closest

Get unique closest ancestors of each matching selection

VariableTypeDefaultDescriptionRequired

filter

selection

-

Filter selection

context

selection

-

Context selection

<div class="js-nav">
    <a class="js-link-account">Your Account</a>
</div>
<div class="nav">
    <a class="js-link-about">About Us</a>
</div>
import $ from 'wee-dom';

$('.js-link-about).closest('.js-nav');
<div class="js-nav">
    <a class="js-link-about">About Us</a>
</div>

This method traverses up the DOM for the closest match. It doesn't match descendants.

$el.contains

Determine if any matching parent selection contains descendant selection

VariableTypeDefaultDescriptionRequired

descendant

selection

-

Descendant selection

import $ from 'wee-dom';

$('ref:element').contains('.descendant');
true

$el.contents

Get unique content of each matching selection

VariableTypeDefaultDescriptionRequired

parent

selection

-

Parent selection

import $ from 'wee-dom';

$('ref:element').contents();

The response includes text and comment nodes.

$el.css

Get CSS value of first matching selection or set value of each matching selection

VariableTypeDefaultDescriptionRequired

a

string, object

-

CSS property to get/set, or an object of properties and their values

value

string

-

Value to assign to property

Get Value

import $ from 'wee-dom';

$('ref:element').css('marginTop');
"0px"

Set Single Value

import $ from 'wee-dom';

$('ref:element').css('marginTop', '5px');

Set Multiple Values

import $ from 'wee-dom';

$('ref:element').css({
    marginTop: '5px',
    color: 'red'
});

$el.data

Get data of first matching selection or set data of each matching selection

VariableTypeDefaultDescriptionRequired

a

string, object

-

Data attribute to get or set or an object

b

string

-

Value to assign to data attribute

Get All

<div data-ref="element" data-id="150"></div>
import $ from 'wee-dom';

$('ref:element').data();
{
    ref: "element",
    id: 150
}

Get Single

<div data-ref="element" data-id="150"></div>
import $ from 'wee-dom';

$('ref:element').data('id');
150

Set Single

import $ from 'wee-dom';

$('ref:element').data('id', '250');

Set Multiple

import $ from 'wee-dom';

$('ref:element').data({
    id: '350',
    active: 'true'
});

$el.empty

Remove child nodes from each matching selection

<div data-ref="bio">
    <h1>John Smith</h1>
    <p>Lorem ipsum dolor.</p>
</div>
import $ from 'wee-dom';

$('ref:bio').empty();
<div data-ref="bio"></div>

$el.eq

Get indexed node of matching selection

VariableTypeDefaultDescriptionRequired

index

number

-

Element index

context

selection

-

Context selection

<ul class="js-element">
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
</ul>
import $ from 'wee-dom';

$('.js-element li').eq(1));
<li>List item 2</li>

Negative Index

import $ from 'wee-dom';

$('.js-element li').eq(-1));
<li>List item 3</li>

$el.filter

Return a filtered subset of elements from a matching selection

VariableTypeDefaultDescriptionRequired

filter

function, selection

-

Filter selection or callback

options

object

-

Callback options

Selection

import $ from 'wee-dom';

$('ref:element').filter('.filter');

Function

The current index and element are injected into the callback. The scope of this is the element.

<ul class="people">
    <li>John Doe</li>
    <li>John Smith</li>
    <li>Jane Doe</li>
    <li>Jane Smith</li>
</ul>
import $ from 'wee-dom';

$('.people li').filter((i, el) => {
    //Return elements containing 'Doe'
    return $text(el).indexOf('Doe') !== -1;
});
[<li>John Doe</li>, <li>Jane Doe</li>]

$el.find

Get unique filtered descendants from each matching selection

VariableTypeDefaultDescriptionRequired

filter

selection

-

Filter selection

import $ from 'wee-dom';

$('table').find('tr');

$el.first

Get the first element of a matching selection

VariableTypeDefaultDescriptionRequired

context

selection

-

Selection context

import $ from 'wee-dom';

const $first = $('ref:element').first();

$el.hasClass

Determine if the matching selection has a class

VariableTypeDefaultDescriptionRequired

className

string

-

Specific class name

Single

<div class="hello" data-ref="element"></div>
import $ from 'wee-dom';

$('ref:element').hasClass('hello');
$('ref:element').hasClass('donuts');
true
false

$el.height

Get or set the height of each matching selection

VariableTypeDefaultDescriptionRequired

value

function, string, number, boolean

-

Height to set, callback, or true to get outer height

Get

import $ from 'wee-dom';

$('ref:element').height();
100

Outer Height

import $ from 'wee-dom';

$('ref:element').height(true);
120

The value returned is a unitless pixel value.

Set

import $ from 'wee-dom';

$('ref:element').height('10rem');

Function

The current index and height are injected into the callback. The scope of this is the element.

<div data-ref="example" style="height: 100px;"></div>
import $ from 'wee-dom';

$('ref:example').height((i, height) => {
    // Increase the height of the element by 50px
    return (height += 50) + 'px';
});

If no unit is provided pixels will be set.

$el.hide

Hide each matching selection

Hide works by adding the js-hide class which applies display: none !important;

import $ from 'wee-dom';

$('ref:element').hide();

$el.html

Get inner HTML of first selection or set each matching selection's HTML

VariableTypeDefaultDescriptionRequired

value

function, string

-

HTML to set or callback

<div data-ref="element"><h1>Heading</h1></div>

Get

import $ from 'wee-dom';

$('ref:element').html();
"<h1>Heading</h1>"

Set

import $ from 'wee-dom';

$('ref:element').html('<h2>New Heading</h2>');

Function

The current index and HTML are injected into the callback. The scope of this is the element.

import $ from 'wee-dom';

$('.js-element').html((el, i, html) => {
    // Return uppercase HTML
    return html.toUpperCase();
});

$el.index

Get the zero-based index of a matching selection relative to it's siblings

<ul>
    <li></li>
    <li></li>
    <li class="js-last"></li>
</ul>
import $ from 'wee-dom';

$('.js-last).index();
2

$el.insertAfter

Insert each matching source selection element after each matching target selection

VariableTypeDefaultDescriptionRequired

target

selection

-

Target selection

import $ from 'wee-dom';

$('ref:element).insertAfter('.js-element');

$el.insertBefore

Insert each matching source selection element before each matching target selection

VariableTypeDefaultDescriptionRequired

target

selection

-

Target selection

import $ from 'wee-dom';

$('ref:element).insertBefore('.js-element');

$el.is

Determine if at least one matching selection matches a specified criteria

VariableTypeDefaultDescriptionRequired

filter

function, selection

-

Filter selection or callback

options

object

-

Callback options

Selection

<div class="js-element"></div>
import $ from 'wee-dom';

$('.js-element').is('div');
true

Function

<ul class="names">
    <li>John Doe</li>
    <li data-hidden="true">Jane Doe</li>
    <li>John Smith</li>
    <li>Jane Smith</li>
</ul>
import $ from 'wee-dom';

$('.names li').is((i, el) => {
    // Check if data-hidden is set to true
    return $(el).is('hidden') === 'true';
});
true

$el.last

Get the last element of a matching selection

VariableTypeDefaultDescriptionRequired

context

selection

-

Context selection

<ul class="names">
    <li>John Doe</li>
    <li>John Smith</li>
    <li>Jane Doe</li>
    <li>Jane Smith</li>
</ul>
import $ from 'wee-dom';

$('.names li').last();
<li>Jane Smith</li>

$el.next

Get the unique next sibling of each matching selection

VariableTypeDefaultDescriptionRequired

filter

selection

-

Filter selection

options

object

-

Callback options

Simple

import $ from 'wee-dom';

$('ref:element').next();

Filtered

<ul>
    <li>John Doe</li>
    <li>John Smith</li>
    <li data-ref="name">Jane Doe</li>
    <li>Jane Smith</li>
</ul>
import $ from 'wee-dom';

$('ref:name').next();
<li>Jane Smith</li>

$el.not

Returns elements not matching the filtered selection

VariableTypeDefaultDescriptionRequired

filter

function, selection

-

Filter selection or callback

options

object

-

Callback options

Selection

import $ from 'wee-dom';

$('ref:element').not('div');

Function

The current index and element are injected into the callback. The scope of this is the element.

<ul class="names">
    <li>John Doe</li>
    <li data-hidden="true">Jane Doe</li>
    <li>John Smith</li>
    <li>Jane Smith</li>
</ul>
import $ from 'wee-dom';

$('.names li').not((i, el) => {
    // Check if data-hidden is set to true
    return $(el).data('hidden') === true;
});
[<li>John Doe</li>, <li>John Smith</li>, <li>Jane Smith</li>]

$el.offset

Get the offset position of a matching selection relative to the document

VariableTypeDefaultDescriptionRequired

value

object

-

Offset values

Set

import $ from 'wee-dom';

$('ref:element').offset({
    top: 100,
    left: 20
});

Get

import $ from 'wee-dom';

$('ref:element').offset();
{
    top: 520,
    left: 30
}

The object values are returned as unitless pixel values.

$el.parent

Get unique parent from each matching selection

VariableTypeDefaultDescriptionRequired

filter

selection

-

Filter selection

Selection Parent

import $ from 'wee-dom';

$('ref:element').parent();

Filtered

Return selection parent only if it matches the filter.

import $ from 'wee-dom';

$('ref:element').parent('main');

$el.parents

Get unique ancestors of each matching selection

VariableTypeDefaultDescriptionRequired

filter

selection

-

Filter selection

import $ from 'wee-dom';

$('ref:element').parents();

$el.position

Get the position of the first matching selection relative to its offset parent

VariableTypeDefaultDescriptionRequired

target

selection

-

Target selection

import $ from 'wee-dom';

$('ref:element').position();
{
    top: 250,
    left: 30
}

The object values are returned as unitless pixel values.

$el.prepend

Prepend selection or markup before each matching selection

VariableTypeDefaultDescriptionRequired

source

function, selection, string

-

Source selection, callback, or HTML string

options

object

-

Callback options

Selection

import $ from 'wee-dom';

$('ref:element').prepend($('.js-element'));

Function

The current index and HTML are injected into the callback. The scope of this is the element.

<h1 data-ref="listHeading">Names</h1>
<ul data-ref="list">
    <li>John Doe</li>
    <li>Jane Doe</li>
</ul>

import $ from 'wee-dom';

$('ref:listHeading').prepend(() => {
    return $('ref:list').children().d + ' ';
});
<h1 data-ref="listHeading">2 Names</h1>
<ul data-ref="list">
    <li>John Doe</li>
    <li>Jane Doe</li>
</ul>

$el.prev

Get the unique previous sibling of each matching selection

VariableTypeDefaultDescriptionRequired

filter

selection

-

Filter selection

options

object

-

Callback options

Simple

import $ from 'wee-dom';

$('ref:element').prev();

Filtered

<ul>
    <li>John Doe</li>
    <li>John Smith</li>
    <li data-ref="name">Jane Doe</li>
    <li>Jane Smith</li>
</ul>
import $ from 'wee-dom';

$('ref:name').prev();
<li>John Smith</li>

$el.prop

Get property of first matching selection or set property of each matching selection

VariableTypeDefaultDescriptionRequired

a

string, object

-

Property to get or set or an object

b

function, string

-

Value to assign to property

Get

import $ from 'wee-dom';

$('ref:element').prop('checked');
true

Single

import $ from 'wee-dom';

$('ref:element').prop('checked', true);

Multiple

import $ from 'wee-dom';

$('ref:element').prop({
    checked: true,
    required: false
});

$el.remove

Remove each matching selection from the document

VariableTypeDefaultDescriptionRequired

context

selection

-

Context selection

import $ from 'wee-dom';

$('ref:element').remove();

$el.removeAttr

Remove specified attribute of each matching selection

VariableTypeDefaultDescriptionRequired

name

string

-

Attribute name

import $ from 'wee-dom';

$('ref:element').removeAttr('title');

$el.removeClass

Remove classes from each matching selection

VariableTypeDefaultDescriptionRequired

value

function, string

-

Class name(s) to remove or callback

Single

import $ from 'wee-dom';

$('ref:element').removeClass('modifier');

Multiple

Separate multiple class names with spaces.

import $ from 'wee-dom';

$('ref:element')removeClass('modifier modifier2');

Function

The current index and class value are injected into the callback. The scope of this is the element.

import $ from 'wee-dom';

$('ref:element')removeClass((i, className) => {
    // Remove an indexed class
    return className + i;
});

$el.replaceWith

Replace each matching selection with selection or markup

VariableTypeDefaultDescriptionRequired

source

function, selection, string

-

Source selection, callback, or HTML string

Selection

import $ from 'wee-dom';

$('ref:element').replaceWith($('.js-element'));

Markup

import $ from 'wee-dom';

$('ref:element').replaceWith('<span>Replacement element</span>');

Function

The current index and HTML are injected into the callback. The scope of this is the element.

<ul class="names">
    <li>John Doe</li>
    <li>Jane Doe</li>
</ul>
import $ from 'wee-dom';

$('.names li').replaceWith((i, html) => {
    return "<li>The " + html + "</li>";
});
<ul class="names">
    <li>The Jane Doe</li>
    <li>The John Doe</li>
</ul>

$el.scrollLeft

Get or set the X scroll position of each matching selection

VariableTypeDefaultDescriptionRequired

value

integer

-

Left position

Get Value

import $ from 'wee-dom';

$('ref:element').scrollLeft();
0

The value returned is a unitless pixel value.

Set Value

import $ from 'wee-dom';

$('ref:element').scrollLeft(15);

Scroll position should be provided as unitless pixel value.

$el.scrollTop

Get or set the Y scroll position of each matching selection

VariableTypeDefaultDescriptionRequired

value

integer

-

Top position

import $ from 'wee-dom';

$('ref:element').scrollTop();
1560

The value returned is a unitless pixel value.

Set Value

import $ from 'wee-dom';

$('body').scrollTop(15);

Scroll position should be provided as unitless pixel value.

$el.serializeForm

Serialize input values from first matching form selection

VariableTypeDefaultDescriptionRequired

json

boolean

false

Convert to JSON

Standard

import $ from 'wee-dom';

$('ref:element').serializeForm();
"inputName=value&inputName2=value2"

JSON

import $ from 'wee-dom';

$('ref:element').serializeForm(true);
{
    "inputName": "value",
    "inputName2": "value2"
}

$el.show

Show each matching selection

Show works by removing the js-hide class either set manually or through $el.hide().

import $ from 'wee-dom';

$('ref:element').show();

$el.siblings

Get unique siblings of each matching selection

VariableTypeDefaultDescriptionRequired

filter

selection

-

Filter selection

<p>Sibling paragraph</p>
<span>Sibling span</span>
<div data-ref="sibling">Target div.</div>

All Siblings

Without a filter all siblings will be returned.

import $ from 'wee-dom';

$('ref:sibling').siblings();
[<p>Sibling paragraph</p>, <span>Sibling span</span>]

Filtered

import $ from 'wee-dom';

$(ref:sibling).siblings('p');
[<p>Sibling paragraph</p>]

$el.slice

Get subset of selection matches from specified range

VariableTypeDefaultDescriptionRequired

start

integer

-

Starting index

end

integer

-

Ending index

import $ from 'wee-dom';

$('li').slice(0, 3);

$el.text

Get inner text of first selection or set each matching selection's text

VariableTypeDefaultDescriptionRequired

value

function, string

-

Text to set or callback

<div class="js-element">Inner text</div>

Get

import $ from 'wee-dom';

$('.js-element').text();
"Inner text"

Set

import $ from 'wee-dom';

$('.js-element').text('New text');

Function

The current index and text are injected into the callback. The scope of this is the element.

import $ from 'wee-dom';

$('.js-element').text((el, i , text) => {
    // Return uppercase text
    return text.toUpperCase();
});

$el.toggle

Toggle the display of each matching selection

Rotates calling the [hide]() and [show]() methods.

import $ from 'wee-dom';

$(ref:element').toggle();

$el.toggleClass

Toggle adding and removing class(es) from the specified element

VariableTypeDefaultDescriptionRequired

className

function, string

-

Class name(s) or callback

state

boolean

-

Force add or remove

Single

import $ from 'wee-dom';

$('ref:element').toggleClass('modifier');

Multiple

Separate multiple class names with spaces.

import $ from 'wee-dom';

$('ref:element').toggleClass('modifier modifier2');

Function

The current index, class value and state are injected into the callback. The scope of this is the element.

import $ from 'wee-dom';

$('.element').toggleClass((i, className, state) => {
    // Return the class intended for toggle
    return className + (state === true ? '-on' : '-off);
});

$el.val

Get value of first matching selection or set values of each matching selection

VariableTypeDefaultDescriptionRequired

value

function, string

-

Class name(s) to add or callback

Get

import $ from 'wee-dom';

$('ref:element').val();

Set

import $ from 'wee-dom';

$('ref:element').val('123');

Function

The current index and value are injected into the callback. The scope of this is the element.

<input type="text" value="This is an ordinary sentence in an input field." data-ref="input">
import $ from 'wee-dom';

$('ref:input').val((i, value) => {
    // Check the length of the current value but don't change the value
    if (value.length > 20) {
        alert('Getting long winded, aren\'t we?');
    }
    return value;
});

$el.width

Get or set the width of each matching selection

VariableTypeDefaultDescriptionRequired

value

function, string

-

Width to set or callback

Get

import $ from 'wee-dom';

$('ref:element').width();
100

The value returned is a unitless pixel value.

Set

import $ from 'wee-dom';

$('ref:element').width('10rem');

Function

The current index and width are injected into the callback. The scope of this is the element.

<div data-ref="example" style="width: 100px;"></div>

import $ from 'wee-dom';

$('ref:example').width((i, width) => {
    // Increase the width of the element by 50px
    return (width += 50) + 'px';
});

If no unit is provided pixels will be set.

$el.wrap

Wrap markup around each matching selection

VariableTypeDefaultDescriptionRequired

html

function, string

-

Wrapper HTML or callback

Markup

import $ from 'wee-dom';

$('ref:element').wrap('<div class="wrapper"></div>');

Function

The current index is injected into the callback. The scope of this is the element.

<div class="library">
    <ul class="books programming">
        <li>JavaScript: The Definitive Guide</li>
        <li>Mastering Regular Expressions</li>
    </ul>
    <ul class="books technique">
        <li>Code Complete</li>
        <li>The Pragmatic Programmer</li>
    </ul>
</div>
import $ from 'wee-dom';

$('.books').wrap(function(i) {
    if ($(this).hasClass('programming')) {
        return '<div class="reference"></div>'
    } else {
        return '<div class="readers"></div>'
    }
});
<div class="library">
    <div class="reference">
        <ul class="books programming">
            <li>JavaScript: The Definitive Guide</li>
            <li>Mastering Regular Expressions</li>
        </ul>
    </div>
    <div class="readers">
        <ul class="books technique">
            <li>Code Complete</li>
            <li>The Pragmatic Programmer</li>
        </ul>
    </div>
</div>

$el.wrapInner

Wrap markup around the content of each matching selection

VariableTypeDefaultDescriptionRequired

html

function, string

-

Wrapper HTML or callback

Markup

import $ from 'wee-dom';

$('ref:element').wrapInner('<div class="wrapper"></div>);

Function

The current index is injected into the callback. The scope of this is the element.

<ul class="names">
    <li class="boss">Jane Doe</li>
    <li>John Doe</li>
</ul>
import $ from 'wee-dom';

$('.names li').wrapInner(function(i) {
    // Wrap bosses in bold tag
    if ($(this).hasClass('boss')) {
        return '<b></b>';
    }
});
<ul class="names">
    <li class="boss"><b>Jane Doe</b></li>
    <li>John Doe</li>
</ul>

$events.addEvent

Add a custom event

VariableTypeDefaultDescriptionRequired

name

string

-

Event name

on

function

-

Enable function

off

function

-

Disable function

import $events from 'wee-events';

$events.addEvent('pressHold', function(el, fn, conf) {
    let scope = this;
    let duration = conf.duration || 400;

    $events.on(el, 'mousedown.pressHold', function(e, el) {
        scope.timer = setTimeout(function() {
            scope.timer = false;

            fn.apply(conf.scope || el, W._slice.call(arguments));
        }, duration);
    }, conf);

    $.on(el, 'mouseup.pressHold', function() {
        if (scope.timer) {
            clearTimeout(scope.timer);
        }
    });
}, function(el, fn) {
    $events.off(el, 'mouseup.pressHold', fn);
});

$events.on('ref:element', 'pressHold', function(e, el) {
    // Trigger logic
});

$events.bound

Get currently bound events to optional specified element, event, and function

VariableTypeDefaultDescriptionRequired

target

selection

-

Target selection

event

string

-

Specific event name

fn

function

-

Specific callback

By default bound will return all bound events.

import $events from 'wee-events';

$events.bound();
[Object, Object, ...]

Selection

$bound('ref:element');
[Object, Object, ...]

selection Event

$bound('ref:element', 'click');
[Object, Object, ...]

$events.off

Remove specified function to specified element and optional event and function

VariableTypeDefaultDescriptionRequired

target

selection

-

Target selection

a

string

-

Event name or object of events

b

function

-

Callback to remove

Target

If no event or callback is provided all element events will be removed.

import $events from 'wee-events';

$events.off('ref:element');

Selection Event

import $events from 'wee-events';

$off('ref:element', 'click');

Selection Event Callback

import $events from 'wee-events';

$events.off('ref:element', 'click', (e, el) => {
    // Click logic
});

Multiple Selections

import $events from 'wee-events';

$events.off({
    'ref:element': {
        mouseenter: function() {
            // Enter logic
        }
    },
    '.js-element': {
        click: function(e, el) {
            // Click logic
            e.preventDefault();
        }
    }
});

Global

You can remove entire groups of namespaced events.

import $events from 'wee-events';

$events.off(false, '.namespace');

$events.on

Bind specified function to specified element and event

VariableTypeDefaultDescriptionRequired

target

selection

-

Target selection

a

string, object

-

Event name or object of events

b

function, object

-

Event callback or options object

c

object

-

Option parameters below

VariableTypeDefaultDescriptionRequired

args

array

-

Callback arguments

context

selection

-

Context selection

delegate

selection

-

Delegate selection

namespace

string

-

Apply namespace to all events

once

boolean

false

Remove the event after first execution

scope

object

-

Callback scope

Simple

import $events from 'wee-events';

$events.on('ref:element', 'click', (e, el) => {
    // Click logic
    e.preventDefault();
});

Once

import $events from 'wee-events';

$events.on('ref:element', 'click', (e, el) => {
    // Click logic
    e.preventDefault();
}, {
    once: true
});

Delegation

import $events from 'wee-events';

$events.on('.js-descendant', 'click', (e, el) => {
    // Click logic
    e.preventDefault();
}, {
    delegate: 'ref:element'
});

Multiple Events

import $events from 'wee-events';

$events.on('ref:element', {
    click: function() {
        // Click logic
    },
    blur: function() {
        // Blur logic
    }
});

Multiple Selections

import $events from 'wee-events';

$events.on({
    'ref:element': {
        mouseenter() {
            // Enter logic
        }
    },
    '.js-element': {
        click(e, el) {
            // Click logic
            e.preventDefault();
        }
    }
});

Namespacing

Events can be namespaced by appending ‘.namespace’ to the end of the event name. Namespaced events can then be selected, modified, and destroyed as a group.

import $events from 'wee-events';

$events.on('ref:element', 'click.namespace', (e, el) => {
    // Click logic
    e.preventDefault();
});
import $events from 'wee-events';

$events.on({
    'ref:element': {
        click(e, el) {
        // Click logic
        e.preventDefault();
    },
    '.js-element': {
        click(e, el) {
            // Click logic
            e.preventDefault();
        }
    }
}, {
    namespace: 'namespace'
});

$events.trigger

Execute event for each matching selection

VariableTypeDefaultDescriptionRequired

target

selection

-

Target selection

event

string

-

Event name

import $events from 'wee-events';

$events.trigger('ref:element', 'click');

$location.uri

Retrieve information about current location or parse a provided URL

Parameters

VariableTypeDefaultDescriptionRequired

url

string

-

URL to be parsed

Return Value

VariableTypeDefaultDescriptionRequired

fullPath

string

-

URL path, query string, and hash

hash

string

-

URL hash value with # omitted

path

string

-

URL path

search

string

-

Query string of URL including ?

query

object

-

Unserialized key/value pairs from search

segments

array

-

Parsed path segments

url

string

-

Full URL value

origin

string

-

Full URL origin

protocol

string

-

http or https

port

string

-

URL port if available

import $location from 'wee-location';

$location.uri('https://origin.com:80/path/to/page?prop1=test#some-hash');
{
    fullPath: '/path/to/page?prop1=test#some-hash',
    hash: 'some-hash',
    path: '/path/to/page',
    search: '?prop1=test',
    query: { prop1: 'test' },
    segments: ['path', 'to', 'page'],
    url: 'https://origin.com/path/to/page?prop1=test#some-hash',
    origin: 'https://origin.com',
    protocol: 'https',
    port: '80'
}

$location.segments

Retrieve the current location's path segments as an array or individual segment by index

Parameters

VariableTypeDefaultDescriptionRequired

index

number

-

Specific index to retrieve from segments array

import $location from 'wee-location';

// Current URL is https://weepower.com/script/location
$location.segments();
$location.segments(1);
['script', 'location']
'location'

$mediator.remove

Remove subscriber by id or all subscribers from topic

Parameters

VariableTypeDefaultDescriptionRequired

topic

string

-

Name of topic

identifier

string, function

-

Subscriber id or registered callback function

Remove by Function

import $mediator from 'wee-mediator';

const callback = function subscriber() {
    console.log('message published to subscriber 1');
};
$mediator.on('message', callback);
$mediator.on('message', () => {
    console.log('message published to subscriber 2');
});

$mediator.remove('message', callback);

$mediator.emit('message');
'message published to subscriber 2'

Remove by Id

import $mediator from 'wee-mediator';

$mediator.on('message', () => {
    console.log('message published to subscriber 1');
});

const subscriber = $mediator.on('message', () => {
    console.log('message published to subscriber 2');
});

$mediator.remove('message', subscriber.id);

$mediator.emit('message');
'message published to subscriber 1'

Remove all Subscribers

import $mediator from 'wee-mediator';

$mediator.on('message', () => {
    console.log('message published to subscriber 1');
});
$mediator.on('message', () => {
    console.log('message published to subscriber 2');
});

$mediator.remove('message'); // Removes all subscribers from this topic

$mediator.on

Subscribe to topic

Parameters

VariableTypeDefaultDescriptionRequired

topic

string

-

Name of topic

callback

function

-

Function to execute upon publication to topic

import $mediator from 'wee-mediator';

$mediator.on('message', (subject, message) => {
    console.log(subject);
    console.log(message);
});

$mediator.emit('message', 'Test', 'Can you hear me?');
'Test'
'Can you hear me?'

$mediator.emit

Publish to topic

Parameters

VariableTypeDefaultDescriptionRequired

topic

string

-

Name of topic

args

*

-

Argument(s) to pass to subscriber callback functions registered with on method

import $mediator from 'wee-mediator';

$mediator.on('message', (subject, message) => {
    console.log(subject);
    console.log(message);
});

$mediator.emit('message', 'Test', 'Can you hear me?');
'Test'
'Can you hear me?'

Matches

A route match represents the state of the current active or previous route. This object is passed as the to and from parameters that are passed into lifecycle methods as well as to other configuration methods such as scrollBehavior and transition.

Properties

VariableTypeDefaultDescriptionRequired

name

string

-

Name of route record

meta

object

{ }

Meta data passed from route record

path

string

-

URL path

hash

string

-

URL hash

query

object

{ }

Query string parsed from URL

search

string

-

Raw URL query string

segments

array

[ ]

URL path segments

params

object

{ }

Parameters extracted from URL path based on route record path

fullPath

string

-

URL path, query, and hash

matched

object

-

All nested path segments of the current route record

transition

object

null

Transition specified on route record

Router

The router is a method that can take an options object. This configuration object will affect how routing behaves.It also has all of the route API methods chained to it. This allows us to initialize routes in one of two ways:

import $router from 'wee-routes';

// With custom configuration
$router({
    scrollBehavior() {},
    transition: {}
}).map().run();

// Using router defaults
$router.map().run();

Options

VariableTypeDefaultDescriptionRequired

scrollBehavior

function

-

Defines scroll position of new page after navigation

transition

object

-

Transition during navigation

Scroll Behavior

When navigating a user with History, we may want to scroll to the top of the page, or preserve the scrolling position of history entries just like the browser does during a full page reload (or some other custom behavior). This is controlled with the scrollBehavior function. The default scroll functionality would look like this if passed in manually to the router:

import $router from 'wee-routes';

$router({
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition;
        } else {
            return { x: 0, y: 0 };
        }
    }
});

Parameters

VariableTypeDefaultDescriptionRequired

to

object

-

Current route match

from

object

-

Previous route match

savedPosition

object

-

Saved x and y values

The savedPosition parameter exists if the navigation was triggered with the popstate event and therefore has the saved scroll state from when the page was previously visited.

Transitions

Transitions allow for a smooth experience when navigating with the router. The most basic implementation looks something like the following:

import $router from 'wee-routes';

$router({
    transition: {
        target: 'body',
        class: '-is-loading',
        timeout: 200
    }
});

Here we are telling the router to apply a given modifier class to a single container element on the page that we want to transition out and back in again.

Note: Make sure transition class target is is not being replaced by PJAX, or the transition will fail.

The expectation with this implementation is that the designated class is applying a CSS transition which means that the target element must stay on the DOM throughout the navigation process. The timeout property is recommended to ensure that transitions work consistently. The value of the timeout property would typically be the same length of time as the transition applied on the target or longer.

Note: The need for a timeout will be corrected in a future version of Wee.

The other implementation uses custom callbacks and looks like the following:

import $router from 'wee-routes';

$router({
    transition: {
        leave(to, from, next) {
            // Custom logic for exiting previous page
            if (! transitionSuccessful) {
              next(new Error('something went wrong'));
            }

            next();
        },
        enter(to, from) {
            // Custom logic for entering newly navigated page
        }
    }
})

Parameters

VariableTypeDefaultDescriptionRequired

to

object

-

Current route match

from

object

-

Previous route match

next

function

-

Callback that continues transition evaluation (leave only)

This implemenation allows you to do anything you can dream up. Passing an error instance will cause the navigation to stop processing and return to the previous page, again same as a before hook.

Transitions can be configured globally or per route. Transitions on a route record will take precedence:

import $router from 'wee-routes';

$router({
    transition: {
        target: 'body',
        class: '-is-loading',
        timeout: 200
    }
}).map([
    {
        path: '/',
        transition: {
            leave() {},
            enter() {}
        }
    }
])

Route Handlers

Route Handlers are special objects that are used throughout an application to define router functionality. They can greatly clean up your route mapping by housing the various functions in their own file/module.

import $router from 'wee-routes';
import about from './about';

$router.map([
    { 
        path: '/about', 
        before() {},
        init() {},
        update() {},
        after() {}
    }
]).run();

// becomes
$router.map([
    { path: '/about', handler: about }
]).run();

In the about module, you would export a RouteHandler instance with some or all of the following methods:

import { RouteHandler } from 'wee-routes';

export default new RouteHandler({
    beforeInit(to, from, next) {
        // ...
    },
    init(to, from) {
        // ...
    },
    beforeUpdate(to, from, next) {
        // ...
    },
    update(to, from) {
        // ...
    },
    unload: 'about',
    after(to, from) {

    }
});

There are other, larger benefits to using Route Handlers besides cleaning up your main route file. Since Route Handlers will live inside page-specific modules, your Route Handler functions will have access to all page-specific variables and data. This works the other direction as well. If you need to dynamically retrieve any data with an AJAX request in a beforeInit hook for a particular page, for example, you can easily pass that data to your page-specific code.

Lastly, Route Handlers can be shared between multiple route records. This can be advantageous because you may, for example, have a common set of logic that you want triggered on every page. However, you may need that common module updated independently, rather than initialized, when the route record is being processed for the first time because the route handler was already initialized on a different route. This is easily achievable with Route Handlers.

import $router from 'wee-routes';
import common from './common';
import home from './home';
import about from './about';

$router.map([
    { path: '/', handler: [common, home] },
    { path: '/about', handler: [common, about] }
]);

$router.run('/'); // home.init and common.init will fire
$router.run('/about'); // about.init and common.update will fire

Handler Methods

Route Handlers have a specific set of possible methods/properties. Many of these are the same as route records, however there are some important additions. beforeUpdate and beforeInit are added to give more control over possible data fetching or module bootstrapping.

OptionDescriptionRequired

beforeInit

Executes before init

beforeUpdate

Executes before update

init

Executes on first evaluation of handler

update

Executes after first evaluation of handler

unload

Executes when leaving route record

after

Executes after all other methods

Lifecycle Methods

Lifecycle methods hook into the router and execute at key points in the route evaluation process.

The following methods can be registered in a route handler and/or directly on route records. Lifecycle methods execute in the order that they are listed.

Parameters

VariableTypeDefaultDescriptionRequired

to

object

-

Current route match

from

object

-

Previous route match

next

function

-

Callback that continues route evaluation (before methods only)

Before

The before method is available only to route records and will execute after the route is matched and before any other registered methods are executed. This method receives a third parameter. This parameter is a function that must be executed before the other methods registered to the route will evaluate.

Fetching Data

Asynchronous actions can be taken from within before, preventing further evaluation of the matched route record until next is executed.

import $router from 'wee-routes';
import admin from './admin';
import $fetch from 'wee-fetch';

$router.map([
    {
        path: '/admin',
        handler: admin,
        before(to, from, next) {
            $fetch('/data.json').then(() => next());
        }
    }
]).run();

Guards

Because the next function must be executed for evaluation of the route record to continue, before methods can act as a guard. You can halt evaluation of the route record by passing false to the next function.

import $router from 'wee-routes';
import admin from './admin';

$router.map([
    {
        path: '/admin',
        handler: admin,
        before(to, from, next) {
            if (notAuthorized) {
              // Stop evaluation and go no further
              next(false);
            } else {
              // Continue
              next();
            }
        }
    }
]).run();

Before Init

The beforeInit method is the same as the before method except that it is available only to route handlers. It will execute after the route is matched and before any other registered methods are executed except a before method registered on the matched record. This method fires only if the previously matched route record is different from the currently matched record.

Before Update

The beforeUpdate method is the same as the before method except that it is available only to route handlers. It will execute after the route is matched and before any other registered methods are executed except a before method registered on the matched record. This method fires if the user navigates to the same page as they were previously.

Init

The init method fires only if the previously matched route record is different from the currently matched record. In simpler terms, the init method fires the first time that the user visits a section of a website. This makes it easier to distinguish initialization of a page from logic that updates a page.

import $router from 'wee-routes';

$router.map([
    { path: '/', init(to, from) {} }
]).run();

Update

The update method fires if the user navigates to the same page as they were previously. A common example of this would be when a filter of some kind is updated by the user that changes the query string value of the URL. The same route record will match, however the page will need to be adjusted to match the constraints of the updated filter.

import $router from 'wee-routes';

$router.map([
    { path: '/', init(to, from) {}, update(to, from) {} }
]).run();

Unload

The unload method evaluates when navigating away from a route. This is relevant when PJAX has been enabled and navigation on the site is using History. In this case, we may need to clean up after ourselves to prevent a memory leak. The unload method makes it easy to do this.

This method takes either function or a namespace. If a namespace is provided, Wee will destroy anything generated or bound by wee-events, wee-screen, and wee-store registered with the same namespace.

import $router from 'wee-routes';
import admin from './admin';
import home from './home';

$router.map([
    { path: '/admin', handler: adminHandler, unload(to, from) {} }, // Providing function
    { path: '/', handler: home, unload: 'home' } // Providing namespace
]).run();

After

The after method will execute after all other methods have completed. Unlike the before method, this method is not passed a next function.

import $router from 'wee-routes';

$router.map([
    { path: '/admin', after(to, from) {} }
]).run();

Records

Route records are objects that map a URL to parts of your application.

When a route record is matched, the callbacks defined on that record are executed in a specific order. At a minimum, route records must consist of a path and either a handler or init property.

Properties

VariableTypeDefaultDescriptionRequired

path

string

-

The URL to be matched

handler

RouteHandler, array

-

Route handler(s) to be evaluated when route is matched

children

array

-

Nested routes

name

string

-

The name of the route object. Records can be referenced by name instead of path

meta

object

-

Custom properties to be passed to matched route record functions

before

function

-

Executes at the beginning of matched route evaluation and before any registered route handler before callbacks

init

function

-

Evaluates the first time that the route is matched

update

function

-

Evaluates in place of init when immediately preceding route match is same as current route match

after

function

-

Executes at the end of matched route evaluation and after any registered route handler after callbacks

unload

function

-

Evaluates when navigating away from current route record

transition

object

-

Transition specific to route (overrides global transition)

Path

The path is the url that you wish to match. Paths can take an assortment of syntaxes. The full list of possible options are described in path-to-regexp, the package that Wee Routes uses for evaluating routes. Below is a description of some of these options.

Wildcards and Parameters

You may use * to indicate a wildcard segment. If you wish to capture that segment and pass it to your function, you use parameters which are names preceded by a colon, i.e :id. Route parameters will be accessible in the route object which is passed to the various callbacks registered on a matched route record.

import $router from 'wee-routes';
import { blog } from './blog';

$router.map([
    { path: '/blog/:id', handler: blog },
    { path: '*', init(to, from) {} }
]).run();

// and in `./scripts/blog`

export function blog(route) {
    // route.params.id will now be the matched segment.
}

Optional Parameters

You can make parameters in a path optional by adding a ? to the end of the parameter. For example we could change the path example above:

{ path: '/blog/:id?', handler: blog }

This route record would now match for either /blog or /blog/1.

Name

The routes name allows you to reference the route by name, regardless of any changes to the path.

import $router from 'wee-routes';
import adminHandler from './admin';

$router.map([
    { name: 'admin', path: '/admin', handler: adminHandler }
]).run();

Meta

Sometimes you may want to pass specific properties into the registered functions for a route record. This can be accomplished through the meta property.

import $router from 'wee-routes';
import adminHandler from './admin';

$router.map([
    { path: '/admin', handler: adminHandler, meta: { isAdmin: true } } 
]).run();

// and in './scripts/admin'
export default new RouteHandler {
    init(to) {
        console.log(to.meta.isAdmin); // true
    }
}

Handler

The handler property can take a Route Handler or an array of Route Handlers.

import $router from 'core/router';
import blogHandler from './blog';
import commonHandler from './common';
import socialHandler from '../components/social';
import commentsHandler from '../components/comments';

$router.map([
    { path: '/', handler: commonHandler },
    {
        path: '/blog/:id',
        handler: [blogHandler, socialHandler, commentsHandler, commonHandler] 
    }
]).run();

Children

You may nest routes under the children key. It will accept an array of routes, structured exactly as the original route record is structured and supports all of the same options.

*Note: You must omit the parent segment from the child paths

When a child route is matched, this causes both the child route and it's parent route to be evaluated (parent -> children).

import $router from 'wee-routes';
import adminHandler from './admin';
import postHandler from './post';

$router.map([
    {
        path: '/admin',
        handler: adminHandler,
        children: [
            { path: 'post', handler: postHandler }
        ]
    }
]).run();

Values

You can easily disable any unneeded breakpoints by setting them to false in wee.json or add more by adding a breakpoint value to this same array.

  1. Portrait Mobile (320px)
  2. Landscape Mobile (480px)
  3. Portrait Tablet (768px)
  4. Desktop 1 (1024px)
  5. Desktop 2 (1280px)
  6. Desktop 3 (1440px)

Wee uses the font family of the HTML element to reference the current breakpoint. For example, the Portrait Mobile breakpoint is triggered when the font family is '2'. When you add/remove default breakpoints, the corresponding font family values will update automatically when the build process is run.

Default Values

  1. Portrait Mobile (320px) - font-family: 1
  2. Landscape Mobile (480px) - font-family: 2
  3. Portrait Tablet (768px) - font-family: 3
  4. Desktop 1 (1024px) - font-family: 4
  5. Desktop 2 (1280px) - font-family: 5
  6. Desktop 3 (1440px) - font-family: 6

Customized Values

  1. Portrait Mobile (320px) - font-family: 1
  2. Landscape Mobile (480px) - font-family: 2
  3. Portrait Tablet (768px) - font-family: 3
  4. Landscape Tablet (900px) - font-family: 4
  5. Desktop 1 (1024px) - font-family: 5
  6. Desktop 2 (1280px) - font-family: 6
  7. Desktop 3 (1440px) - font-family: 7
  8. Desktop 4 (1600px) - font-family: 8

$store.push

Add a value to an array

Parameters

VariableTypeDefaultDescriptionRequired

key

string

-

Property name

value

*

-

Value to be added to array

prepend

boolean

false

Add value to beginning of array instead of the end

import $store from 'wee-store';

$store.push('key', 1); // Will create array if property does not yet exist
$store.push('key', 2);
$store.push('key', 3, true); // Prepend value

$store.get('key');
$store.get('key.0');
[3, 1, 2]
3

$store.concat

Merge arrays together

Parameters

VariableTypeDefaultDescriptionRequired

key

string

-

Property name

value

array

-

Value to be merged into existing value

prepend

boolean

false

Add value to beginning of array instead of the end

import $store from 'wee-store';

$store.concat('key', 1); // Will create array if property does not yet exist
$store.concat('key', [2, 3]);
$store.concat('key', [4, 5], true); // Prepend value

$store.get('key');
[4, 5, 1, 2, 3]

$store.merge

Extend object

Parameters

VariableTypeDefaultDescriptionRequired

key

string

-

Property name

value

object

-

Object to be extended into existing value

import $store from 'wee-store';

// Will create array if property does not yet exist
$store.merge('key', {
    key1: 1
});
$store.merge('key', {
    key2: 2
});

$store.get('key');
{ key1: 1, key2: 2 }

$store.drop

Delete property

Parameters

VariableTypeDefaultDescriptionRequired

key

string

-

Property name

Remove by Key

import $store from 'wee-store';

// Will create array if property does not yet exist
$store.set('key', {
    key1: 1,
    key2: 2
});
$store.drop('key.key1');

$store.get('key');
{ key2: 2 }

Remove by Value

import $store from 'wee-store';

// Will create array if property does not yet exist
$store.set('key', [1, 2, 3]);
$store.drop('key', 2);

$store.get('key');
[1, 3]

$store.has

Check if property or value exists

Parameters

VariableTypeDefaultDescriptionRequired

key

string

-

Storage property

value

*

-

Storage value

Check Key

import $store from 'wee-store';

$store.set('key', {
    key1: 'Don'
});
$store.has('key.key1');
true

Check Value

import $store from 'wee-store';

$store.set('key', [1, 2, 3]);
$store.has('key', 2);
$store.has('key', 4);
true
false

$store.set

Set property

Parameters

VariableTypeDefaultDescriptionRequired

key

string

-

Property name

value

*

-

Property value

options

object

{ }

See callback options

Simple

import $store from 'wee-store';

$store.set('key', true);

Function

import $store from 'wee-store';

$store.set('key', function(greeting, subject) {
    if (this.inclusive) {
        subject = 'world';
    }

    return `${greeting} ${subject}!`;
}, {
    scope: { inclusive: true },
    args: ['Hello', 'Jim']
});
Hello world!

$store.get

Retrieve property

Parameters

VariableTypeDefaultDescriptionRequired

key

string

-

Property name

fallback

*

-

Fallback value if property does not exist

set

boolean

false

Set value if property doesn't exist

options

object

{ }

See callback options

Simple

import $store from 'wee-store';

$store.set('key', true);
$store.set('otherKey', false);
$store.get('key');
true
$store.get('notSet');
null

Retrieve all data

// Continuation of Simple example above
$store.get();
{ key: true, otherKey: false }

Fallback

$store.get('key', 'Fallback');
$store.get('key');
Fallback
null

Set Value

$store.get('key', 'Fallback', true);
$store.get('key');
Fallback
Fallback

$store.destroy

Destroy store instance

import $store from 'wee-store';

const $storeInstance = $store.create('test');

$storeInstance.destroy();

$store.configure

Sometimes, you may need to update settings on an existing store instance. This is most applicable to the default store module that is automatically generated. If you wanted to enable browser storage on the default module, for example, you could do this:

$store.configure({ browserStorage: 'session' });
VariableTypeDefaultDescriptionRequired

options

object

{ }

Options object below

Options Object

VariableTypeDefaultDescriptionRequired

browserStorage

string

-

Enable browser storage to persist data from store instance - local or session

keepInMemory

boolean

true

Keep data set on store instance in memory (must be true unless browserStorage is enabled)

$setVar

Refresh all store instances from data in DOM

VariableTypeDefaultDescriptionRequired

context

selection

document

Context to search within

Document

<body>
    <meta data-set="key" data-value="true">
    ...
<body>

Set Variables from Document

import { $setVar } from 'wee-store';

$setVar();

Retrieval

import $store from 'wee-store';

$store.get('key');
true

$store.setVar

Refresh specific store instance from data in DOM

VariableTypeDefaultDescriptionRequired

context

selection

document

Context to search within

Document

<body>
    <meta data-store="test" data-set="key" data-value="true">
    ...
<body>

Set Variables from Document

import $store, { $setVar } from 'wee-store';

const testStore = $store.create('test');

testStore.setVar();

Retrieval

testStore.get('key');
true

$store.create

Create new store instance

Parameters

VariableTypeDefaultDescriptionRequired

name

string

-

Name of store instance

options

object

{ }

Store options below

Options Object

VariableTypeDefaultDescriptionRequired

browserStorage

string

-

Enable browser storage to persist data from store instance - local or session

keepInMemory

boolean

true

Keep data set on store instance in memory (must be true unless browserStorage is enabled)

prefix

string

'wee'

Prefix for storage key used to set browser storage if enabled

import $store from 'wee-store';

const cartStore = $store.create('cart', { 
    browserStorage: 'local',
    prefix: 'mysite'
});

cartStore.set('quantity', 2); // Data stored in localStorage under 'mysite_cart'
cartStore.get('quantity');
2