pax

This is the main PAX library, encapsulating the xmlHttpRequest obj, event handeling with request queue management, event binding, and so on.

Author

Mikkel Bergmann, http://www.pointful.com

Summary
paxThis is the main PAX library, encapsulating the xmlHttpRequest obj, event handeling with request queue management, event binding, and so on.
Properties
paxMain library OBJ
pax.docRootString to prefix all server calls with, useful for ensuring security is not broken easily
pax.requestQueueArray of requests.
pax.showStatusSpinnerBoolean to choose if we should display the status spinner
pax.statusSpinnerContainerThe default container (DOM Element) to put the statusbox spinner into.
pax.bindQueueList of functions bound to objects.
pax.resourcePathPath to the resource directory
pax.statusSpinnerImageThe default image to use for the spinner, relative to the resource path
pax.idCounterUnique ID counter for generating temporary DOM IDs
pax.showDebugOutputs debug to console in certain instances, if true
Functions
$Alias to document.getElementById, if $ is already defined: _$ becomes the old $.
pax.postSend a POST request via the XMLHttpRequest object.
pax.getSend a GET request via the XMLHttpRequest object.
pax.getIdReturns the current unique ID
pax.getNextIdIncrements the unique ID counter, and returns the ID
pax.event.bindAdd an event to an OBJ
pax.event.bindOneBinds the event once only, ie: clears any other bound functions on the event first.
pax.event.hasBindingReturns true if an object has a certain event bound to the given function.
pax.event.unbindRemove an event from an OBJ
pax.event.unbindAllRemove all registered events from all OBJs.
pax.event.bindKeyDownBinds a key down event to an object
pax.event.bindKeyUpBinds a key up event to an object
pax.event.bindKeyPressBinds a key press event to an object.
pax.scopeBrings the scope of an object into the current scope, with the optional given name.
pax.unJSONConverts a JSON string to an object.
pax.postStringURL encodes an oject into a post string to be used in pax.post.
pax.postParamsURL decodes a post string back into a set of parameters
pax.defaultArgsOverrides default arguments in the given object only if they exist in the given argument
pax.defAddArgsOverrides default arguments in the given object, and adds any other attributes in the argument
pax.hideStatusHides the status spinners.
pax.setCallBackSet the onreadystatechange to a callback function, which calls the given function.
pax.cancelCancel the pax call, and destroy request object

Properties

pax

Main library OBJ

pax.docRoot

String to prefix all server calls with, useful for ensuring security is not broken easily

pax.requestQueue

Array of requests.

pax.showStatusSpinner

Boolean to choose if we should display the status spinner

pax.statusSpinnerContainer

The default container (DOM Element) to put the statusbox spinner into.

pax.bindQueue

List of functions bound to objects.  {obj:object, event:event, func:function}

pax.resourcePath

Path to the resource directory

pax.statusSpinnerImage

The default image to use for the spinner, relative to the resource path

pax.idCounter

Unique ID counter for generating temporary DOM IDs

pax.showDebug

Outputs debug to console in certain instances, if true

Functions

$

var _$ = $; var $ = function $(id)

Alias to document.getElementById, if $ is already defined: _$ becomes the old $.

WIP: Detect other libraries, such as jquery, prototype, yui, ext, etc; use _$ to fix it up...

Parameters

idThe id of the DOM element

Example

<div id='myElement'>This is my Elements innerHTML</div>
[:.
    var ele = $('myElement');
    alert( ele.innerHTML );
:]

Assigns a pointer to ele, and the alerts the contents.

pax.post

pax.post = function(url,
post,
callBack,
callDesc,
spinnerBox,
spinnerImage)

Send a POST request via the XMLHttpRequest object.  Note that you do not need to specify all parameters

Parameters

urlURL to send a request to.
postPOST string to include in the call, use pax.postString to encode an object containing key / value pairs
callBackFunction to call once the request responds.
callDescDescription of what the request is doing - is displayed as a title for the status spinner.
spinnerBoxDOM element to put the spinners into
spinnerImageImage to use as request spinner.

Note that a callback function needs 3 parameters

xmlIf the response is in XML format, this will contain the response, otherwise it will be empty
txtIf the response is in Text format, this will contain the response, otherwise it will be empty
urlwhat URL the response came from

Example

<div id='pax.post.example1'></div>
[:.
    var mycallBack = function( xml, txt, url ) {
        var response = pax.unJSON( txt );
        $('pax.post.example1').innerHTML = "The name retreived from the server is: " + response.data[0].name;
    };
    pax.post( '/pax/pax.post.example.php', pax.postString( { action: 'editAction', id: 2 } ), mycallBack, 'Post example', 'pax.post.example1' );
:]

This will send a request, with id = 2, action = ‘editAction’, showing the default spinner image via the spinner queue.  It should be noted that the php script has a 2 second delay, so that you actually see the spinner.

Example

<div id='pax.post.example2'></div>
[:.
    var mycallBack = function( xml, txt, url ) {
        var response = pax.unJSON( txt );
        $('pax.post.example2').innerHTML = "The country retreived from the server is: " + response.data[0].country;
    };
    pax.post( '/pax/pax.post.example.php', pax.postString( { action: 'editAction', id: 1 } ), mycallBack, 'Post example', 'pax.post.example2', 'load_snake_blue.gif' );
:]

This will send a request, with id = 1, action = ‘editAction’, showing a custom spinner image via the spinner queue.  It should be noted that the php script has a 2 second delay, so that you actually see the spinner.

pax.get

pax.get = function(url,
callBack,
callDesc,
spinnerBox,
spinnerImage)

Send a GET request via the XMLHttpRequest object.  Note that you do not need to specify all parameters

Parameters

urlURL to send a request to.
callBackFunction to call once the request responds.
callDescDescription of what the request is doing - is displayed as a title for the status spinner.
spinnerBoxDOM element to put the spinners into
spinnerImageImage to use as request spinner.

Note that a callback function needs 3 parameters

xmlIf the response is in XML format, this will contain the response, otherwise it will be empty
txtIf the response is in Text format, this will contain the response, otherwise it will be empty
urlwhat URL the response came from

Example

<fieldset><legend>Response from pax.get</legend>
    <div id='pax.get.example1'></div>
</fieldset>
[:.
    var url = '/pax/pax.get.example1.txt';

    var callBack = function( xml, txt, url ) {
        $('pax.get.example1').innerHTML = txt;
    };

    pax.get( url, callBack, 'get example', false, false );
:]

Note

You can add a timestamp at the end of the URL, to make it unique, to avoid caching issues in certain browsers

pax.getId

pax.getId = function()

Returns the current unique ID

Parameters

none

Example

pax.getNextId

pax.getNextId = function()

Increments the unique ID counter, and returns the ID

Parameters

none

Example

pax.event.bind

pax.event.bind = function(obj,
event,
func)

Add an event to an OBJ

Parameters

objectDOM Object to attach the event / function to
eventThe event we’re listening for.  Note that we don’t add the ‘on’ part
funcFunction to run when event fires

Example

<div id="pax.event.bind.example1">Click me!</div>
[:.
    pax.event.bind( $('pax.event.bind.example1'), 'click', function() { alert('Thanks for clicking!') } );
:]

Alerts when the div’s onclick function fires.

Notes

  • To avoid memory leaks, the bind function automatically adds an pax.event.unbindAll function call to window.onunload
  • It is best practice to NOT to assign local closure variables to an outside reference.

If you use

var el = document.getElementById(‘exampleWindowCloseButton’); pax.event.bind( el, ‘click’, function() {...

Then the memory leak will occur.  If you use

pax.event.bind( $(‘exampleWindowCloseButton’), ‘click’, function() {...

Then there is no memory leak, as pax.unbindAll will clear the binding before we unload the window.

pax.event.bindOne

pax.event.bindOne = function(obj,
event,
func)

Binds the event once only, ie: clears any other bound functions on the event first.

pax.event.hasBinding

pax.event.hasBinding = function(obj,
event,
func)

Returns true if an object has a certain event bound to the given function.  This uses the pax.bindQueue

Parameters

objectDOM Object we’re inspecting
eventThe event we’re testing for.  Note that we don’t add the ‘on’ part
funcFunction that we’re testing for

Example

<div id="pax.event.hasBinding.example1"></div>
[:.
    var myFunc = function() {
        alert('Thanks for clicking!');
    };
    var box = $('pax.event.hasBinding.example1');
    box.innerHTML += 'has binding: ' + pax.event.hasBinding( box, 'click', myFunc ) + '<bR>';
    box.innerHTML += 'adding binding...<bR>';
    pax.event.bind( box, 'click', myFunc );
    box.innerHTML += 'has binding: ' + pax.event.hasBinding( box, 'click', myFunc ) + '<bR>';
    box.innerHTML += 'removing binding...<bR>';
    pax.event.unbind( box, 'click', myFunc );
    box.innerHTML += 'has binding: ' + pax.event.hasBinding( box, 'click', myFunc ) + '<bR>';
:]

pax.event.unbind

pax.event.unbind = function(obj,
event,
func)

Remove an event from an OBJ

Parameters

objectDOM Object to remove the event from
eventThe event we assigned originally.  Note that we don’t add the ‘on’ part
funcFunction that was assigned to run when event fires

Example

<div id="pax.event.unbind.example1">Click me!</div>
[:.
    var cluck = function() {
        pax.event.unbind( $('pax.event.unbind.example1'), 'click', cluck );
        alert('Thanks for clicking! Now click OK, and try again. It wont work the 2nd time, as we have unbound the function.');
    };
    pax.event.bind( $('pax.event.unbind.example1'), 'click', cluck );
:]

Removes the previously bound function event.

Example

<div id="pax.event.unbind.example2">Click me!</div><input type='button' id="pax.event.unbind.example2.button" value='Unbind'>
[:.
    var cluck1 = function() { console.log('1'); };
    var cluck2 = function() { console.log('2'); };
    pax.event.bind( $('pax.event.unbind.example2'), 'click', cluck1 );
    var unbindCluck = function() {
        pax.event.unbind( $('pax.event.unbind.example2'), 'click' );
        alert('Thanks for clicking! Now click OK, and try again. It wont work the 2nd time, as we have unbound the function.');
    };
    pax.event.bind( $('pax.event.unbind.example2'), 'click', cluck2 );
    pax.event.bind( $('pax.event.unbind.example2.button'), 'click', unbindCluck );
:]

Removes all previously bound click events.

pax.event.unbindAll

pax.event.unbindAll = function(unbindObj)

Remove all registered events from all OBJs.  This method is automatiacally called on window unload.

Note

There is no example, as it would break the example window’s functionality.  It removes all previously bound function events.

pax.event.bindKeyDown

pax.event.bindKeyDown = function(obj,
func)

Binds a key down event to an object

Parameters

objectDOM Object to bind the keydown event to
funcFunction that runs when the key fires

Example

Type in this box: <input type="text" id="pax.event.bindKeyDown.keyInput"> Key code: <input type="text" id="pax.event.bindKeyDown.keyPressed" size="3">
[:.
    var myKeyFunc = function( event ) {
        $('pax.event.bindKeyDown.keyPressed').value = event.keyCode;
    };
    pax.event.bindKeyDown( $('pax.event.bindKeyDown.keyInput'), myKeyFunc );
:]

This will show what keycode is returned when you press a key in the first text box

pax.event.bindKeyUp

pax.event.bindKeyUp = function(obj,
func)

Binds a key up event to an object

Parameters

objectDOM Object to bind the keyup event to
funcFunction that runs when the event fires

Example

Type in this box: <input type="text" id="pax.event.bindKeyUp.keyInput"> Key code: <input type="text" id="pax.event.bindKeyUp.keyPressed" size="3">
[:.
    var myKeyFunc = function( event ) {
        $('pax.event.bindKeyUp.keyPressed').value = event.keyCode;
    };
    pax.event.bindKeyUp( $('pax.event.bindKeyUp.keyInput'), myKeyFunc );
:]

This will show what keycode is returned when you press a key, then let go of it, in the first text box

pax.event.bindKeyPress

pax.event.bindKeyPress = function(obj,
action)

Binds a key press event to an object.  The reason we have this method is that it will work in all browsers

Parameters

objectDOM Object to bind the keypress event to
funcFunction that runs when the event fires

Example

Type in this box: <input type="text" id="pax.event.bindKeyPress.keyInput">
Key code: <input type="text" id="pax.event.bindKeyPress.keyPressed" size="3">
[:.
    var myKeyFunc = function( event ) {
        $('pax.event.bindKeyPress.keyPressed').value = event.keyCode;
    };
    pax.event.bindKeyPress( $('pax.event.bindKeyPress.keyInput'), myKeyFunc );
:]

This will show what keycode is returned when you press a key in the first text box

pax.scope

pax.scope = function(obj,
name)

Brings the scope of an object into the current scope, with the optional given name.  If no name is specified, then it is assumed an object with ‘name’ -> value is passed, and each variable will be available as ‘name’.  The global variable is simply a copy, and is not linked to the local variable

Parameters

objobject to put into global name space
nameoptional name to use for the object; if no name is given, the object will be traversed, and the items in it will be globalised.

Example

Type before global scope: <div id='pax.scope.example1.type' style='border: 1px solid red'></div>
Type after global scope: <div id='pax.scope.example1.typeAfter' style='border: 1px solid green'></div>
[:.
    var globalise = function () {
        var localVariable = "local";
        pax.scope( localVariable, 'gVar' );
    };
    $('pax.scope.example1.type').innerHTML = typeof(gVar) + '<b' + 'r>';
    globalise();
    $('pax.scope.example1.typeAfter').innerHTML = typeof(gVar) + '<b' + 'r>';
:]

This example brings a variable from the scope of the function, into the current scope.

Example

Log: <div id='pax.scope.example1.log' style='border: 1px solid black'></div>
[:.
    var myFunc = {
        init: function ( value ) {
            this.variable = value;
        },
        scopalise: function() {
            pax.scope( this.variable, 'gvar2' );
        },
        log: function( header) {
            var t = $('pax.scope.example1.log');
            t.innerHTML += '[' + header + ']<b' + 'r> local type: <b>' + typeof(this.variable) + '</b> value: <b>' +
                this.variable + '</b><b' + 'r>global type: <b>' + typeof(gvar2) + '</b>';
            if( typeof(gvar2) != 'undefined' )t.innerHTML += ' value: <b>' + gvar2 + '</b>';
            t.innerHTML += '<hr>';
        }
    };
    myFunc.init( 'I\'m a local' );
    myFunc.log( 'before scopalise' );
    myFunc.scopalise();
    myFunc.log( 'after scopalise' );
    gvar2 = "I\'m a global";
    myFunc.log( 'change scopalised variable' );
:]

This example brings a variable from the scope of the function, into the current scope, and shows that it is just a copy, not the actual variable.

pax.unJSON

pax.unJSON = function(jsonStr)

Converts a JSON string to an object.  This method is only here because it is best practice to do it this way.

Parameters

jsonStrthe string to convert.

Example

<div id='pax.unJSON.example1'></div>
[:.
    var myFruitString = "{  'apples': ['Granny Smith', 'Red delicious'], ";
    myFruitString += "      'oranges': ['Valencia', 'Blood'], ";
    myFruitString += "      'pears': 'green' }";
    var myFruits = pax.unJSON( myFruitString );
    $('pax.unJSON.example1').innerHTML = pax.util.toString(myFruits);
:]

Will return an object with this shape:

{ ‘apples’: [ ‘Granny Smith’, ‘Red delicious’ ], ‘oranges’: [ ‘Valencia’, ‘Blood’ ], ‘pears’: ‘green’ }

pax.postString

pax.postString = function(param)

URL encodes an oject into a post string to be used in pax.post.

Parameters

paraman object containing key / value pairs to be encoded

Example

Before: <div id='pax.postString.example1.before'></div>
After: <div id='pax.postString.example1.after'></div>
[:.
    var postObj = { id: 23, action: 'update' };
    var myPost = pax.postString( postObj );
    $('pax.postString.example1.before').innerHTML = pax.util.inspect(postObj);
    $('pax.postString.example1.after').innerHTML = myPost;
:]

When this is run, myPost becomes ‘&id=23&action=update’

pax.postParams

pax.postParams = function(string)

URL decodes a post string back into a set of parameters

Parameters

stringa string to be decoded into parameters

pax.defaultArgs

pax.defaultArgs = function(obj,
args)

Overrides default arguments in the given object only if they exist in the given argument

Parameters

objan object containing key / value pairs to be overridden
argsan object containing optional key / value pairs to override the contents of obj

Example

Before: <div id='pax.defaultArgs.example1.before'></div>
After: <div id='pax.defaultArgs.example1.after'></div>
[:.
    var config = { name: 'Bob Smith', email: 'bob@smith.com', action: 'update' };
    $('pax.defaultArgs.example1.before').innerHTML = pax.util.toString( config );
    pax.defaultArgs( config, { action: 'insert' } );
    $('pax.defaultArgs.example1.after').innerHTML = pax.util.toString( config );
:]

Changes config to contain the action ‘insert’

pax.defAddArgs

pax.defAddArgs = function(obj,
args)

Overrides default arguments in the given object, and adds any other attributes in the argument

Parameters

objan object containing key / value pairs to be overridden
argsan object containing optional key / value pairs to override the contents of obj

Example

Before: <div id='pax.defaultArgs.example1.before'></div>
After: <div id='pax.defaultArgs.example1.after'></div>
[:.
    var config = { name: 'Bob Smith', email: 'bob@smith.com', action: 'update' };
    $('pax.defaultArgs.example1.before').innerHTML = pax.util.toString( config );
    pax.defaultArgs( config, { action: 'insert' } );
    $('pax.defaultArgs.example1.after').innerHTML = pax.util.toString( config );
:]

Changes config to contain the action ‘insert’

pax.hideStatus

pax.hideStatus = function()

Hides the status spinners.

Parameters

none

pax.setCallBack

pax.setCallBack = function(url,
callBack,
callDesc,
spinnerBox,
spinnerImage)

Set the onreadystatechange to a callback function, which calls the given function.  Also shows hides the status spinner as required.

Parameters

urlURL to send a request to.
callBackFunction to call once the request responds.
callDescDescription of what the request is doing - is displayed as a title for the status spinner.
spinnerBoxDOM element to put the spinners into, false = don’t use
spinnerImageImage to use as request spinner, false = don’t use

Example

This method is only useful if you’re overriding one of the request methods, such as pax.get or pax.post

<fieldset><legend>Response from Request Object</legend>
    <div id='pax.setCallBack.example1'></div>
</fieldset>
[:.
    var url = '/pax/pax.getRO.example1.txt';

    var callBack = function( xml, txt, url ) {
        $('pax.setCallBack.example1').innerHTML = txt;
    };

    var myRObj = pax.setCallBack( url, callBack, 'setCallBack example', false, false );
    myRObj.ro.open( 'GET', url, true );
    myRObj.ro.send( null );
:]

This will send a request, and receive a response via using the setCallBack method.

pax.cancel

pax.cancel = function(robj)

Cancel the pax call, and destroy request object

Parameters

robjRequest object to cancel call from

Example

<div id='pax.cancel.example1'></div>
[:.
    var mycallBack = function( xml, txt, url ) {
        var response = pax.unJSON( txt );
        $('pax.cancel.example1').innerHTML = "The name retreived from the server is: " + response.data[0].name;
    };
    var myRO = pax.post( '/pax/pax.post.example.php', pax.postString( { action: 'editAction', id: 2 } ), mycallBack, 'Post example', 'pax.cancel.example1' );

    window.setTimeout( function() { pax.cancel( myRO.ro ); $('pax.cancel.example1').innerHTML = 'Cancelled request'; }, 1000 );
:]

This example creates a call that takes 2000ms, then cancels the call after 1000ms

var _$ = $; var $ = function $(id)
Alias to document.getElementById, if $ is already defined: _$ becomes the old $.
pax.post = function(url,
post,
callBack,
callDesc,
spinnerBox,
spinnerImage)
Send a POST request via the XMLHttpRequest object.
pax.get = function(url,
callBack,
callDesc,
spinnerBox,
spinnerImage)
Send a GET request via the XMLHttpRequest object.
pax.getId = function()
Returns the current unique ID
pax.getNextId = function()
Increments the unique ID counter, and returns the ID
pax.event.bind = function(obj,
event,
func)
Add an event to an OBJ
pax.event.bindOne = function(obj,
event,
func)
Binds the event once only, ie: clears any other bound functions on the event first.
pax.event.hasBinding = function(obj,
event,
func)
Returns true if an object has a certain event bound to the given function.
pax.event.unbind = function(obj,
event,
func)
Remove an event from an OBJ
pax.event.unbindAll = function(unbindObj)
Remove all registered events from all OBJs.
pax.event.bindKeyDown = function(obj,
func)
Binds a key down event to an object
pax.event.bindKeyUp = function(obj,
func)
Binds a key up event to an object
pax.event.bindKeyPress = function(obj,
action)
Binds a key press event to an object.
pax.scope = function(obj,
name)
Brings the scope of an object into the current scope, with the optional given name.
pax.unJSON = function(jsonStr)
Converts a JSON string to an object.
pax.postString = function(param)
URL encodes an oject into a post string to be used in pax.post.
pax.postParams = function(string)
URL decodes a post string back into a set of parameters
pax.defaultArgs = function(obj,
args)
Overrides default arguments in the given object only if they exist in the given argument
pax.defAddArgs = function(obj,
args)
Overrides default arguments in the given object, and adds any other attributes in the argument
pax.hideStatus = function()
Hides the status spinners.
pax.setCallBack = function(url,
callBack,
callDesc,
spinnerBox,
spinnerImage)
Set the onreadystatechange to a callback function, which calls the given function.
pax.cancel = function(robj)
Cancel the pax call, and destroy request object
List of functions bound to objects.
Close