Nov 27, 2008

The utility functions

The library comes with many predefined objects and utility functions. The obvious goal of these functions is to save you a lot of repeated typing and idioms.

The $() function

The $() function is a handy shortcut to the all-too-frequent document.getElementById() function of the DOM. Like the DOM function, this one returns the element that has the id passed as an argument.

Unlike the DOM function, though, this one goes further. The returned element object will be augmented with some extra methods. These extra methods simplify many tasks, like hiding/showing the element, getting its size, scrolling to the element, etc. You can get a \list of the methods that are added to the returned element object in the reference for the Element.Methods object. Furthermore, if the element is a form it will also receive copies of the utility methods from Form.Methods and if the element is a form field (input, select, or textarea) it will additionally receive copies of the utility methods from Form.Element.Methods.

<html>
<head>
<title>Prototype examples</title>

<script type="text/javascript" src="prototype.js">

</script>
<script type="text/javascript" language="javascript">

<!--

function toggle(divId)
{
var d = $(divId);
d.hide();
alert(d.innerHTML);
d.show();
d.addClassName('active');
}
-->
</script>

</head>


<body>

<p>Click test button to check the result:</p>

<div id="firstDiv">

<p>This is first paragraph</p>

</div>

<div id="secondDiv">

<p>This is another paragraph</p>

</div>

<input type="button" value="Test $()-First" onclick="toggle('firstDiv');"/>

<input type="button" value="Test $()-Second" onclick="toggle('secondDiv');"/>

</body>

</html>

Because many of the new methods added to the element return the element itself, you can chain the method calls to make more compact code:

//change the text, the CSS class, and make the element visible
$('messageDiv').update('Your order was accepted.').addClassName('operationOK').show();

Another nice thing about this function is that you can pass either the id string or the element object itself, which makes this function very useful when creating other functions that can also take either form of argument.

Using the $$() function

The $() function will help you a lot if you consistently separate CSS from the content wireframe. It parses one or more CSS filtering expressions, analogous to the ones used to define CSS rules, and returns the elements that match these filters.

It's so easy to use it's ridiculous.

function test$$()
{
/*
in case CSS is not your forte, the expression below says
'find all the INPUT elements that are inside
elements with class=field that are inside a DIV
with id equal to loginForm.'
*/
var f = $$('div#loginForm .field input');
var s = '';
for(var i=0; i
s += f[i].value + '/';
}
alert(s); // shows: "joedoe1/secret/"

//now passing more than one expression
f = $$('div#loginForm .field input', 'div#loginForm .fieldName');
s = '';
for(var i=0; i
s += ( f[i].value ? f[i].value : f[i].innerHTML ) + '/';
}
alert(s); //shows: "joedoe1/secret/User name:/Password:/"
}

Using the $F() function
The $F() function is another welcome shortcut. It returns the value of any field input control, like text boxes or drop-down lists. The function can take as argument either the element id or the element object itself. Using

function test3()
{
alert( $F('userName') );
}


Using the $A() function
The $A() function converts the single argument it receives into an Array object.

This function, combined with the extensions for the Array class, makes it easier to convert or copy any enumerable list into an Array object. One suggested use is to convert DOM NodeLists into regular arrays, which can be traversed more efficiently. See example below.

function showOptions()
{
var someNodeList = $('lstEmployees').getElementsByTagName('option');
var nodes = $A(someNodeList);
nodes.each(function(node)
{
alert(node.nodeName + ': ' + node.innerHTML);
});
}


Using the $H() function
The $H() function converts objects into enumerable Hash objects that resemble associative arrays.

function testHash()
{
//let's create the object
var a = {
first: 10,
second: 20,
third: 30
};

//now transform it into a hash
var h = $H(a);
alert(h.toQueryString()); //displays: first=10&second=20&third=30
}

Using the $R() function
The $R() function is simply a short hand to writing new ObjectRange(lowerBound, upperBound, excludeBounds).


function demoDollar_R()
{
var range = $R(10, 20, false);
range.each(function(value, index){
alert(value);
});
}


Using the Try.these() function
The Try.these() function makes it easy when you want to, ahem, try different function calls until one of them works. It takes a number of functions as arguments and calls them one by one, in sequence, until one of them works, returning the result of that successful function call.

In the example below, the function xmlNode.text works in some browsers, and xmlNode.textContent works in the other browsers. Using the Try.these() function we can return the one that works.


function getXmlNodeValue(xmlNode)
{
return Try.these(
function() {return xmlNode.text;},
function() {return xmlNode.textContent;}
);
}

No comments: