baseJS Documentation

baseJS is a lightweight Javascript framework for Safari, Firefox and Mobile Safari. Its original intention is to provide shortcuts for writing Javascript so that your code can use the smallest footprint possible for mobile browsing.

Get baseJS on GitHub.

base

Extending objects in a clean and easy-to-read manner is the core of baseJS. At its root is the base object.

Available Methods and Properties

extend(destination[, …], properties)

An easy method for applying a set of properties, methods, variables onto an object or multiple objects. The last argument is always the object that will be applied to the previous arguments.

Parameter Type Description Optional
destination(s) object Objects that will be extended with properties ×
properties object Object to extend onto the destination(s) ×
Examples
var myObject = function(a) { return a*2; }
base.extend(myObject, { property1: 'Lorem', property2: 'Ipsum' });
base.extend(myObject.prototype, { method: function() {} });

In this example, we've created an object myObject that returns a*2. In the second line, we are assigning a few properties to the myObject variable. In the third line, we see the shortcut for creating multiple methods on myObject.prototype. This shortens the amount of code you will have to write and the verbosity of looking at multiple instance of myObject.prototype.methodName = function() {}.

base.extend(Array.prototype, NodeList.prototype, { method: function() {} });

Alternatively, you can add an indefinite number of objects to have the last object of properties and methods applied to. In this instance, method() will now be a function available on both Arrays and NodeLists.

browser

Properties

base.browser.version // 531. Number browser version, according to the userAgent. base.browser.webkit // true. Boolean browser is WebKit. base.browser.opera // true. Boolean browser is Opera. base.browser.msie // true. Boolean browser is Internet Explorer. base.browser.mozilla // true. Boolean browser is Mozilla/Firefox. base.browser.msafari // true. Boolean browser is Mobile Safari (iPhone and iPod Touch).

isArray(object)

Check if an object is an Array. JavaScript does not have any default method for doing this.

Parameter Type Description Optional
object object Object to check. ×
Example

var myObj = {}; var myArr = []; base.isArray(myObj); // returns false base.isArray(myArr); // returns true

toQueryString(object)

Convert an associative object to a query string for passing as parameters to POST or GET calls.

Parameter Type Description Optional
object object Object to transcribe into a query string. ×
Example

var person = { first_name: 'Paul', last_name: 'Armstrong' }; base.toQueryString(person); // "first_name=Paul&last_name=Armstrong"


Array.prototype, NodeList.prototype

Available Methods and Properties

each(iterator, context)

Iterate a function over each index inside the Array.

Parameter Type Description Optional
iterator function Function to run on each object key ×
context object Scope override ×
Examples

var team = ['Paul', 'Zach', 'Jesse']; var awesome = function(person) { alert(person); }; team.each(awesome); // alerts → 'Paul' then 'Zach' then 'Jesse'

var team = ['Paul', 'Zach', 'Jesse']; var awesome = function(person) { this[person] = true; }; team.each(awesome, team); // applies team.Paul, team.Zach and team.Jesse as true

eachAfter(iterator, interval, direction, context, callback)

Same method as each(), but applies waits over the interval (in milliseconds) to apply to each item in the Array. This is a regular interval method and will prevent your scripts from continuing until it has completed.

Parameter Type Description Optional
iterator function Function to run on each object key ×
interval Number Number of milliseconds before each iteration is run (default 1000) ×
dir Number -1, 1 or null. Negative gives reverse iteration. Defaults to 1.
context object Scope override. Defaults to none.
callback function Function to fire after each item has been iterated. Defaults to empty function.

document

Available Methods and Properties

fire(eventName[, memo])

This method allows you a shorthand for firing custom events from the document object. If you include a memo object when firing the event, it can be recalled by using the event input variable, such as event.memo.

Parameter Type Description Optional
eventName string Name of the event ×
memo object Memo parameters for the event. Defaults empty object.
Examples

function customCallback(event) { alert(event.type); // alerts → 'myEvent' } document.addEventListener('myEvent', customCallback, true); // at some other point in your application document.fire('myEvent');

dom:loaded event

A custom event has been included in baseJS that is fired on the document object called dom:loaded. This can be useful when you need to perform DOM manipulation before the page is rendered or you want to add event listeners prior to the user being able to interact with the page.

Examples

function myPreRenderFxn() { /* … */ } document.addEventListener('dom:loaded', myPreRenderFxn, true);


Element

Available Methods and Properties

Element(type[, atts, content])

A helper method for quickly creating new HTMLElements with attributes.

Parameter Type Description Optional
type string The type of element to create. ×
atts object Attributes to attached to the HTMLElement. Defaults to empty object.
content string Set the innerHTML of the element. Defaults to empty string.
Examples

new Element('a', { class: 'topLink', href: '#top' }, 'Back to Top'); // Returns the HTMLElement <a class="topLink" href="#top">Back to Top</a>


Event

Available Methods and Properties

stop()

Shortcut to preventDefault and stopPropagation on events.

Example

// Stop all links on the page from continuing to their destination href $('a').each(function(el) { el.addEventListener('click', function(event) { event.stop(); }, true); });


Function.prototype

Available Methods and Properties

bind(oScope[, arguments…])

Override the execution scope of a function with object and optionally prepend arguments to the input.

Parameter Type Description Optional
oScope object Object to override the scope of the function. ×
arguments * Any additional arguments to pass.
Examples

var example = function() { this.name = 'My awesome example'; setTimeout(function() { alert(this); // alerts → Window this.sayName(); // error → window.sayName() is undefined }, 100); setTimeout(function() { alert(this); // alerts → Object example this.sayName(); }.bind(this), 100); }; example.prototype.sayName = function() { alert(this.name); // alerts → 'My awesome example' }; var a = new example();

bindAsEventListener(object[, arguments…])

Binding method specific for Event Listener callbacks.

Parameter Type Description Optional
oScope object Object to override the scope of the function. ×
arguments * Any additional arguments to pass.
Examples

var obj = { name: 'A nice demo' }; function handler(event) { alert(this.name); } document.body.addEventListener('click', handler.bindAsEventListener(obj)); // Now any click on the page alerts obj.name


HTMLElement.prototype

Available Methods and Properties

addClass(className)

Add a class to an element if it doesn't already have it.

Parameter Type Description Optional
className string Name of the class to add. ×
Examples

document.body.addClass('body'); // <body class="body">

hasClass(className)

Check if element has a given class name

Parameter Type Description Optional
className string Name of the class to test against. ×
Examples

document.body.hasClass('body'); // true or false

removeClass(className)

Safely remove a className from the HTMLElement by checking surrounding whitespace and/or the beginning and end of the class attribute. Uses the hasClass() method.

Parameter Type Description Optional
className string Name of the class to remove. ×
Examples

document.body.removeClass('body'); // true or false

toggleClass(className)

If the HTMLElement has the specified className, remove it, otherwise add it.

Parameter Type Description Optional
className string Name of the class to remove. ×
Examples

document.body.toggleClass('body'); // returns the element

getXY()

Simplified get X and Y position of an element on a page. Does not compute from within scrolled elements.

This method takes no arguments.

Examples

var nav = document.getElementById('nav'); alert(nav.getXY()); // alerts Array → [xPosition, yPosition] alert(nav.getXY().x); // alerts → xPosition alert(nav.getXY().y); // alerts → yPosition

fire(eventName[, memo])

This method allows you a shorthand for firing custom events from any HTMLElement object. If you include a memo object when firing the event, it can be recalled by using the event input variable, such as event.memo.

Parameter Type Description Optional
eventName string Name of the event ×
memo object Memo parameters for the event. Defaults to empty object.
Examples

function customCallback(event) { alert(event.type); // alerts → 'myHtmlEvent' } var myElement = $('#nav')[0]; myElement.addEventListener('myHtmlEvent', customCallback, true); // at some other point in your application myElement.fire('myHtmlEvent');


io

io is a set of methods for XHR/AJAX functions.

Available Methods and Properties

io(url[, options])

Create a new XHR object request.

Parameter Type Description Optional
url string Location to query through XHR. ×
options object Override settings for making the XHR request.
Optional keys for the options attribute.
Parameter Type Description Optional
method string post or get form method
asynchronous boolean Only true supported at this time.
contentType string Content mime type to send.
encoding string Content encoding.
params object Object of header parameters to send with the request.
format string Response type assumption: 'text', 'json', 'object', 'xml'
sanitizeJSON boolean Whether the JSON needs to be sanitized.
onUninitialized function Ready state callback.
onConnected function Ready state callback.
onRequested function Ready state callback.
onProcessing function Ready state callback.
onComplete function Ready state callback. Includes response object.
onFailure function Ready state callback. Includes response object. (recommended)
onSuccess function Ready state callback. Includes response object. (recommended)
Examples

new io('/test/results.json', { format: 'json', onSuccess: function(o) { alert(o); }, onFailure: function() { alert('There was an error getting the data'); } });


String.prototype

Common methods performed on a String for convenience.

Available Methods and Properties

blank()

Check if a string is empty or only contains whitespace.

This method takes no arguments.

Examples

var myString = 'My awesome string.'; var myEmptyString = ''; myString.blank(); // returns → false myEmptyString.blank(); // returns → true

toHTML()

Convert a string into an HTML NodeList.

This method takes no arguments.

Examples

var newHTML = '<h1><a href="#home">Home</a><span>Go Home</span></h1>'; var header = document.getElementByID('header'); header.appendChild(newHTML.toHTML()[0]); // Append the entire node structure, starting at the first element to the #header element.

trim([match])

Trim any trailing whitespace from a string or optionally provide a string/regular expression selector to match against and remove from the input string.

Parameter Type Description Optional
match string Regular Expression string to trim. Defaults to trailing whitespace.
Examples

var myString = 'Oops look at the whitespace '; myString.trim(); // returns → 'Oops look at the whitespace'; var daveString = 'Remove all instances of Dave. After this, Dave will not exist.'; daveString.trim(/\sDave/g); // returns → 'Remove all instances of. After this, will not exist.'


Template

A Template is used when you have a group of objects that need to be parsed into the same formatted output. Templates are meant to be reused.

Available Methods and Properties

new Template(string)

Create a template. Replaceable keys use #{key} syntax within the string.

Parameter Type Description Optional
template string The markup that will be used for the template. ×
Examples

var myTemplate = new Template('#{name} is #{age} years old.');

parse(object)

Parse the data object into the template, replacing #{key} with key values.

Parameter Type Description Optional
object object Key/value pairs to parse into the template object. ×
Examples

var myTemplate = new Template('#{name} is #{age} years old.'); var person1 = { name: 'Jimmy', age: '22' }; var person2 = { name: 'Janey', age: '23' }; myTemplate.parse(person1); // returns → 'Jimmy is 22 years old.' myTemplate.parse(person2); // returns → 'Janey is 23 years old.'


Utility Methods

Available Methods and Properties

$(selector[, context])

Use CSS selectors to get an Array or NodeList of elements in the document or context, if provided.

Parameter Type Description Optional
selector string CSS query of selectors. ×
context HTMLElement Context for the query. Limits scope of query.
Examples

var header = $('#header')[0]; // Selects the first object on the page with ID 'header' var awesome = $('div.awesome', header); // Selects every instance of <div class="awesome"></div> in #header

From this point, it's possible to run the Array & NodeList methods on the variable awesome.


License

Creative Commons License
baseJS by Paul Armstrong is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.
Based on a work at paularmstrongdesigns.com.
Permissions beyond the scope of this license may be available at http://paularmstrongdesigns.com/projects/basejs.