Fleegix.js reference


This page describes the modules in the Fleegix.js JavaScript toolkit, and the different methods they contain. Click on a module or method name for a detailed description.

Contents


Events


The Fleegix.js event system provides a convenient and flexible way to connect together either DOM events or events in your application. It also provides a basic publish/subscribe system to allow decentralized communiation between the pieces of your Web UI.

fleegix.event.listen

Syntax

fleegix.event.listen(listenerObj, triggerEventName, someFunction); (calling just a simple function)

fleegix.event.listen(listenerObj, triggerEventName, someObject, someMethodName); (calling a method of an object)

Parameters

listenerObj (Object) -- Object to add the listener to.

triggerEventName (String) -- Name of method or event which will trigger execution of a function or method.

someFunction (Function) -- Function to execute when the triggering event is run.

someObject (Object) -- Object with the method you want to execute when the triggering event is run.

someMethodName (String) -- Name of the method you want to execute when the triggering event is run.

Description

Allows you to trigger a function or method whenever a DOM event fires, or a method of some object is invoked. Whenever the triggering event or method is fired, the attached method or function will run. Multiple functions or methods can be attached to the same trigger.

Examples

function simpleAlert() {
  alert('simple');
}

var zardoz = new function () {
  this.foo = function () {
    alert('ABC');
  };
}

var logansRun = new function () {
  this.bar = function () {
    alert('123');
  };
}

fleegix.event.listen(zardoz, 'foo', simpleAlert);
zardoz.foo(); => two alerts, 'ABC,' then 'simple.'

fleegix.event.listen(zardoz, 'foo', logansRun, 'bar');
zardoz.foo(); => now three alerts, 'ABC,' 'simple,' then '123.'

fleegix.event.unlisten

Syntax

fleegix.event.unlisten(listenerObj, triggerEventName, someFunction); (with a simple function)

fleegix.event.unlisten(listenerObj, triggerEventName, someObject, someMethodName); (with a method of an object)

Parameters

listenerObj (Object) -- Object to remove the listener from.

triggerEventName (String) -- Name of method or event which you want to stop triggering a certain function or method.

someFunction (Function) -- Function to stop triggering when the triggering event is run.

someObject (Object) -- Object with the method you want to stop from executing when the triggering event is run.

someMethodName (String) -- Name of the method you want to stop from executing when the triggering event is run.

Description

Removes an attached listener so it will no longer trigger the function or method specified. Use 'unlisten' with the exact same parameters you passed to 'listen' to remove that particular listener.

Examples

function simpleAlert() {
  alert('simple');
}

var zardoz = new function () {
  this.foo = function () {
    alert('ABC');
  };
}

var logansRun = new function () {
  this.bar = function () {
    alert('123');
  };
}

fleegix.event.listen(zardoz, 'foo', logansRun, 'bar');
zardoz.foo(); => two alerts, 'ABC,' then '123.'

fleegix.event.unlisten(zardoz, 'foo', logansRun, 'bar');
zardoz.foo(); => now just one alert, 'ABC.'

fleegix.event.publish

Syntax

fleegix.event.publish(channelName, publishPayload);

Parameters

channelName (String) -- Name of the channel to publish on.

publishPayload (Object) -- Object to send to anyone listening on the specified channel.

Description

Allows an object to publish to a specific channel (simply named with a string), and pass a JavaScript object to anyone subscribed, as a payload of the publish-event.

Examples

var pubObj = {
    thisProp: 'foo',
    thatProp: function () {},
    theOtherProp: 2112 };

fleegix.event.publish('sciFi' pubObj);

fleegix.event.subscribe

Syntax

fleegix.event.subscribe(channelName, subscriberObj, handlerMethod);

Parameters

channelName (String) -- Name of the channel to listen for publish-events on.

subscriberObj (Object) -- Object that is listening for publish-events on that channel.

handlerMethod (Function) -- Method to invoke when the publish-event occurs. The publish event will pass this method a JavaScript Object as a parameter.

Description

Allows an object to listen for published events on a specific channel (simply named with a string), and specify a handler method that will be fired on each publish-event, and be handed a JavaScript object as the publish-event payload.

Examples

var zardoz = new function () {
  this.handlePublish = function (pubObj) {
    alert(pubObj.thisProp);
  };
}

fleegix.event.subscribe('sciFi', zardoz, 'handlePublish'); 

var pubObj = {
    thisProp: 'foo',
    thatProp: function () {},
    theOtherProp: 2112 };

fleegix.event.publish('sciFi' pubObj); => passes pubObj to
handlePublish method of zardoz, which alerts 'foo.'

fleegix.event.unsubscribe

Syntax

fleegix.event.unsubscribe(channelName, unsubscribeObj);

Parameters

channelName (String) -- Name of the channel to unsubscribe from.

unsubscribeObj (Object) -- Object that should stop listening to that channel.

Description

Allows an object that's subscribed to a particular publishing channel to stop listening.

Examples

fleegix.event.unsubscribe('sciFi', zardoz');

XHR


The XHR module has two convenience methods for doing the standard GET and POST requests, as well as the ability to do requests with more detailed control (such as using arbitrary HTTP methods such as PUT, or setting authentication headers or the format of the response). Uses XHR-object pooling and request queueing.

fleegix.xhr.doGet

Syntax

fleegix.xhr.doGet(handlerFunction, url, [responseFormat]); (Asynchronous requests)

fleegix.xhr.doGet(url, [responseFormat]); (Synchronous requests)

Parameters

handlerFunction (Function) -- function called when an asynchronous XHR request returns. If first argument is missing, doGet assumes a synchronous (blocking) request. When called by the response, it will be passed two parameters -- the response in the desired format, and the request ID.

url (String) -- The URL to make the request to.

responseFormat (String) -- Optional parameter, sets the format of the response passed to the handler function. Possible values are 'text' (to pass the responseText of the XHR object), 'xml' (the responseXML), and 'object' (to get the XHR object itself) Defaults to 'text.'

Description

Makes an XHR GET request, and passes the result to the specified handler function.

Examples

function alertResponse(resp, id) {
  alert(resp);
  alert('Request ID was: ' + id);
}
fleegix.xhr.doGet(alertResponse, 'random_textfile.txt');

var s = fleegix.xhr.doGet('random_textfile.txt');
alert(s);

function alertStatus(resp, id) {
  alert(resp.status);
}
fleegix.xhr.doGet(alertResponse, 'random_textfile.txt', 
    'object');

fleegix.xhr.doPost

Syntax

fleegix.xhr.doPost(handlerFunction, url, dataPayload, [responseFormat]); (Asynchronous requests)

fleegix.xhr.doPost(url, dataPayload, [responseFormat]); (Synchronous requests)

Parameters

handlerFunction (Function) -- function called when an asynchronous XHR request returns. If first argument is missing, doPost assumes a synchronous (blocking) request. When called by the response, it will be passed two parameters -- the response in the desired format, and the request ID.

url (String) -- The URL to make the request to.

dataPayload (String) -- Data payload to send with the request.

responseFormat (String) -- Optional parameter, sets the format of the response passed to the handler function. Possible values are 'text' (to pass the responseText of the XHR object), 'xml' (the responseXML), and 'object' (to get the XHR object itself) Defaults to 'text.'

Description

Makes an XHR POST request, and passes the result to the specified handler function.

Examples

function alertResponse(resp, id) {
  alert(resp);
}
fleegix.xhr.doPost(alertResponse, 'random_textfile.txt',
  'foo=bar&baz=2112');

var s = fleegix.xhr.doPost('random_textfile.txt', 
  'foo=bar&baz=2112');
alert(s);

function alertStatus(resp, id) {
  alert(resp.status);
  alert('Request ID was: ' + id);
}
fleegix.xhr.doGet(alertResponse, 'random_textfile.txt', 
  'foo=bar&baz=2112', 'object');

fleegix.xhr.doReq

Syntax

fleegix.xhr.doReq(requestOptions); (Either asynchronous or synchronous)

Parameters

requestOptions (Object) -- Options for the XHR request. Here is the list of possible properties to set, and the default values if they are not set:

Description

Makes an XHR request, with fine-grained control over the type of request, type of response, as well as many other options.

Examples

fleegix.xhr.doReq({
  url: 'some_page.rbx',
  handleAll: function (s) { alert(s.status); },
  responseFormat: 'object',
  uber: true
} );

fleegix.xhr.abort

Syntax

fleegix.xhr.abort(requestId);

Parameters

requestId (Number) -- Request ID of a currently processing XHR request to abort.

Description

If the request is still processing, will abort it and return true. If the request identified by requestId is not currently processing (i.e., it may have already completed), returns false.

Examples

var id = fleegix.doGet(handlerFunction, 
  '/some_file.rbx'); // Get a request ID number
fleegix.xhr.abort(id); // Abort the request

XML


Has a basic XML parser that converts a set of same-named XML tags (i.e, a tag list such as a set of search results) into an array of JavaScript Objects.

fleegix.xml.parse

Syntax

fleegix.xml.parse(xml);

Parameters

xml (Object) -- DOM-compatible Document object.

Description

Parses a list of XML tags into an equivalent array of JavaScript objects. Tag names are converted to property names, and tag values are converted to property values (all Strings).

Examples

function handleUserList(xml) {
  var users = fleegix.xml.parse(xml);
  var userCount = users.length;
  var firstUserUsername = users[0].username;
}

fleegix.xhr.doGet(handleUserList, 'user_list.rbx', 'xml');

Forms


The Fleegix.js forms module contains a number of helpful functions for working with forms, including a serialize function for submitting data via XHR, a restore function which can pre-populate a form from a its serialized data, a form-to-hash converter, and a diff method which allows you to compare two different forms (useful in telling what a user has changed in a form).

fleegix.form.serialize

Syntax

fleegix.form.serialize(formElement, [serializeOptions]);

Parameters

formElement (Object) -- The HTML form you want to serialize.

serializeOptions (Object) -- Options for how to serialize the form. Here is the list of possible properties to set, and the default values if they are not set:

Description

Transforms all the values of form elements in an HTML form into a query-string-style string, usually to be submitted as the payload in an XMLHttpRequest POST request.

Examples

var someForm = document.getElementById('someFormId');
var str = fleegix.form.serialize(someForm);
fleegix.xhr.doPost(handlerFunc, '/post_page.rbx', str);
=> Posts contents of someForm to post_page.rbx

var someForm = document.getElementById('someFormId');
var str = fleegix.form.serialize(someForm, { includeEmpty: true });
var url = 'get_page.rbx?' + str;
fleegix.xhr.doGet(handlerFunc, url);
=> Use the serialized form as a query string in a GET

fleegix.form.restore

Syntax

fleegix.form.restore(formElement, serializedString);

Parameters

formElement (Object) -- The HTML form you want to restore from a string.

serializedString (String) -- The query-string-style string of serialized form data you want to use to restore the form-element values.

Description

Allows you to restore a blank form to the state it was in when it was serialized to a string. This can be nice if you don't want to fill your server-side code with a bunch of conditionals to pre-fill a form from values in the database.

Examples

function getDataAndRestore(userId) {
  fleegix.xhr.doGet(doRestore,
        '/get_user_settings.rbx?userId=' + userId);
}

function doRestore(str) {
  var settingsForm = document.getElementById('settingsForm');
  fleegix.form.restore(settingsForm, str);
}

getDataAndRestore();
=> Pulls the original serialized form data used to save the
user settings, and uses them to pre-fill the form

fleegix.form.toHash

Syntax

fleegix.form.toHash(formElement);

Parameters

formElement (Object) -- The HTML form you want to convert to a keyword/value object.

Description

Transforms all the values of form elements in a form into a keyword/value object (hash). When a form element has multiple values (like with sets of checkboxes, or multi-select select boxes), the values will be put into an array.

All form elements will have a key in the hash. Empty form elements (e.g., a blank text box) will have a value of null in the hash.

Examples

var someForm = document.getElementById('someFormId');
someForm.firstTextBox.value = 'foo';
var obj = fleegix.form.toHash(someForm);
alert(obj.firstTextBox); => alerts 'foo.'

fleegix.form.diff

Syntax

fleegix.form.diff(updatedForm, originalForm, [diffOptions]);

Parameters

updatedForm (Object) -- Form (or form converted to keyword/value object with fleegix.form.toHash) that you want to compare to another form.

originalForm (Object) -- Another form (or converted to keyword/value object with fleegix.form.toHash) that you want to compare to the first one.

diffOptions (Object) -- Currently only one option:

intersectionOnly: false -- If this flag is set to true, will only return fields that are in both forms. The default behavior is to return fields as 'different' if they are only in one form and not the other (i.e., a union).

Description

Allows you to tell how many fields and which fields are different between two forms, as well as what the values are for each differing field for both forms. changed field.

One practical use for this method is figuring what has changed in a form since it initially loaded. The easy way to do this is to make a backup of the form values with fleegix.form.toHash, and then compare the updated form to the original form data in the backed-up object.

This method returns an object with two properties:

  1. count: The number of changed fields
  2. diffs: a keyword/value object containing an item for each field that has changed. The value of the item is an array where the first item is the changed value, and the second is the original value.

Examples

// Get a ref to the form
var someForm = document.getElementById('someFormId');

// Set the value of a text box to 'foo'
someForm.firstTextField.value = 'foo';

// Make a copy of the data in the form
var backupOfForm = fleegix.form.toHash(someForm);

// Change the text box value to something else
someForm.firstTextField.value = 'bar';

// Let's see what changed
var changes = fleegix.form.diff(someForm, backupOfForm);

alert(changes.count); => alerts '1.'
alert(changes.diffs.firstTextField[0]); => alerts 'bar.'
alert(changes.diffs.firstTextField[1]); => alerts 'foo.'

Effects


A new effects module which provides the two most useful visual effects for a Web app -- fade-in and fade-out.

fleegix.fx.fadeOut

Syntax

fleegix.fx.fadeOut(domElement, [fadeOptions]);

Parameters

domElement (Object) -- DOM node (such as div or span) that you wish to apply a fadeout animation effect to.

fadeOptions (Object) -- Options for the fadeout animation. Here is the list of possible properties to set, and the default values if they are not set:

Description

Does a basic opacity fadeout animation effect on the desired DOM element. The element should be set to 100% opacity before applying the effect.

Examples

var fadeDiv = document.getElementById('someDiv');
fleegix.fx.fadeOut(fadeDiv);

fleegix.fx.fadeIn

Syntax

fleegix.fx.fadeIn(domElement, [fadeOptions]);

Parameters

domElement (Object) -- DOM node (such as div or span) that you wish to apply a fadein animation effect to.

fadeOptions (Object) -- Options for the fadein animation. Here is the list of possible properties to set, and the default values if they are not set:

Description

Does a basic opacity fadein animation effect on the desired DOM element. The element should be set to zero opacity before applying the effect.

Examples

var fadeDiv = document.getElementById('someDiv');
fleegix.fx.fadeIn(fadeDiv);

JSON


Contains a function for serializing a JavaScript object to the JSON data format.

fleegix.json.serialize

Syntax

fleegix.json.serialize(serializeObj);

Parameters

serializeObj (Object) -- Object to serialize as a JSON string.

Description

Serializes a JavaScript object into a JSON (http://www.json.org/) string.

Examples

var obj = { name: 'Rush', 
    members: ['Geddy', 'Neil', 'Alex'], album: 2112 };
var str = fleegix.json.serialize(obj);

URI


The URI module in Fleegix.js contains a number of functions for working with URIs -- specifically query strings. With these functions you can grab values out of query-string parameters, or update query-string parameters with new values.

fleegix.uri.getQuery

Syntax

fleegix.uri.getQuery(urlString);

Parameters

urlString (String) -- The URL you want to get the query string from.

Description

Returns the query string (i.e, the portion after the question mark) on a URL.

Examples

var query = fleegix.uri.getQuery(location.href);

fleegix.uri.getBase

Syntax

fleegix.uri.getBase(urlString);

Parameters

urlString (String) -- The URL you want to get the base URL from.

Description

Returns the base URL (i.e, the portion before the question mark, if there's a query string) on a URL.

Examples

var base = fleegix.uri.getBase(location.href);

fleegix.uri.getParam

Syntax

fleegix.uri.getParam(paramName, querystring);

Parameters

paramName (String) -- The name of the parameter you want to get the value of.

querystring (String) -- The query string you want to get a value from.

Description

Returns the value of a parameter on a query string. If the same parameter name appears multiple times in the query string, the function will return an array of all the values.

Examples

var query = 'foo=2112&bar=howdy&foo=1001';
var foo = fleegix.uri.getParam('foo', query);
foo = foo.join();
alert(foo); => alerts '2112,1001.'

fleegix.uri.setParam

Syntax

fleegix.uri.setParam(paramName, value, querystring);

Parameters

paramName (String) -- The name of the parameter you want to set the value of.

value (String) -- The value you want to set the parameter to.

querystring (String) -- The query string you want to set a value for a param on.

Description

Sets the value of a parameter in a query string. If the param is not in the string, it appends it with the desired value at the end of the string. If the entire string is empty, it creates a query string with the single param and value in it.

If the parameter is in the query string multiple times, the function will set the value of the first instance of the param that it finds in the string.

Examples

var query = 'foo=2112&bar=howdy&foo=1001';
var foo = fleegix.uri.setParam('bar', 'wowzers', query);
alert(query); => alerts 'foo=2112&bar=wowzers&foo=1001.'

Cookies


A nice, clean wrapper for getting and setting cookie values in the browser.

fleegix.cookie.set

Syntax

fleegix.cookie.set(cookieName, [opts]);

Parameters

cookieName (String) -- Name of the cookie you want to set the value for.

opts (Object) -- Object with keyword options for the cookie. Here is the list of possible properties to set, and the default values if they are not set:

Description

Sets the value of the cookie with the specified name and path. Days, hours, and minutes for the duration of the cookie may be used in combination. If no opts are passed, assumes '/' for path, and the cookie will expire when the user closes the browser,

Examples

fleegix.cookie.set('loginId');

fleegix.cookie.set('Zardoz', { path: '/app/main', hours: 2, 
  minutes: 30 });

fleegix.cookie.get

Syntax

fleegix.cookie.get(cookieName, [path]);

Parameters

cookieName (String) -- Name of the cookie you want to get the value for.

path (String) -- Path for the cookie you want to get the value for. If omitted, assumes root ('/').

Description

Gets the value of the cookie with the specified name and path.

Examples

fleegix.cookie.get('loginId');

fleegix.cookie.destroy

Syntax

fleegix.cookie.destroy(cookieName, [path]);

Parameters

cookieName (String) -- Name of the cookie you want to remove.

path (String) -- Path for the cookie you want to remove. If omitted, assumes root ('/').

Description

Removes the cookie with the specified name and path.

Examples

fleegix.cookie.remove('loginId');

Popups


Yes, even in the Ajax world, people still use pop-up windows. The Fleegix.js pop-up module gives you a simple way to invoke pop-up windows, but keep the amount of UI clutter to a minimum by enforcing a one-window limit.

fleegix.popup.open

Syntax

fleegix.popup.open(url, [popupOptions]);

Parameters

url (String) -- URL for the location of the popup window

popupOptions (Object) -- Options for the window to be opened. Here is the list of possible properties to set, and the default values if they are not set:

Description

Opens a popup window with the desired set of options. If no options are passed, it simply opens a normal new browser window.

This implementation allows only a single popup window at a time, to keep things simple for end-users. Calling the open method again will simply open the new URL in the same window.

Examples

fleegix.popup.open('/search_window.rbx', 
  { width: 480, height: 300 });

fleegix.popup.close

Syntax

fleegix.popup.close();

Parameters

(None)

Description

Closes the popup window opened with fleegix.popup.open.

Examples

fleegix.popup.open('/search_window.rbx', 
  { width: 480, height: 300 });
fleegix.popup.close();

Copyright 2007 Matthew Eernisse, mde@fleegix.org.