Thursday, December 26, 2013

Developer Notes for prototype.js

covers version 1.5.0

last update: August 18th 2007

Table of Contents

What is that?

In case you haven't already used it, prototype.js is a JavaScript library initially written by Sam Stephenson. This amazingly well thought and well written piece of standards-compliant code takes a lot of the burden associated with creating rich, highly interactive web pages that characterize the Web 2.0 off your back.
When I first started trying to use this library, a few years ago, I noticed that the documentation was definitely not one of its strongest points. As many other developers before me, I got my head around prototype.js by reading the source code and experimenting with it. I thought it would be nice to take notes while I learned and share with everybody else.
I'm also offering an un-official reference for the objects, classes, functions, and extensions provided by this library.
As you read the examples and the reference, developers familiar with the Ruby programming language will notice an intentional similarity between Ruby's built-in classes and many of the extensions implemented by this library. That's not surprising since prototype.js is a spinoff and is directly influenced by the requirements of the Ruby on Rails framework.
As far as browser support goes, prototype.js tries to support Internet Explorer (Windows) 6.0+, Mozilla Firefox 1.5+, Apple Safari 1.0+, and Opera 9+. Supporting these browsers also cause some other browsers that share their rendering engines to be supported as well, like Camino, Konqueror, IceWeasel, Netscape 6+, SeaMonkey, etc.

Related article

Advanced JavaScript guide.

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.

Using 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 (inputselect, or textarea) it will additionally receive copies of the utility methods fromForm.Element.Methods.


 Test Page 






	
This is a paragraph
This is another paragraph
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. Check this out.


User name:
Password:
A quick note on performance. The current implementation of the $$() function in prototype.js is not regarded as particularly efficient. If you plan on traversing deep and complex HTML documents using this function frequently, you may want to consider other freely available implementations, possibly simply substituting the $$() function itself.

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 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.




 
			

Using the $H() function

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

			

Using the $R() function

The $R() function is simply a short hand to writing new ObjectRange(lowerBound, upperBound, excludeBounds).
Jump to the ObjectRange class documentation for a complete explanation of this class. In the meantime, let's take a look at a simple example that also shows the usage of iterators through the each method. More on that method will be found in the Enumerable object documentation.


 
			

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 theTry.these() function we can return the one that works.

			

Tricked out strings

Strings are powerful objects. Prototype.js takes that power and elevates it by another level of magnitude.

String substitutions

When it comes string substitutions JavaScript already has the methods like String.Replace, which even works with regular expressions, but it's still not as flexible as the alternative introduced by prototype.js.
Meet the new String.gsub method. With this method you can not only find and replace a fixed string or a regular expression pattern, but you also have much more control over the replacement process. You can, for example, use a string template to instruct the method on how you would like the found elements to be transformed (rather than simply replaced.)
The example below searches for words containing 't' and replaces the portion that comes after the 't' with 'tizzle', in a lame shot at being funny. In case the example is not very clear, the regular expression we chose has a capture group declaration: the \w+ enclosed in parenthesis. We can get the value captured by this group using #{1} in the replacement template string.
In our example we are capturing what comes before the 't' and appending 'tizzle' to it. If we had more capture groups in the regular expression, we would get the values with #{2}#{3}, and so on.

			
Let's not stop there. The substitution we have just made is not all that powerful because we are limited to pattern matching and substitutions. What if we could operate on the matches with custom logic to produce the desired substitution vaues? We can do that if we pass a function as the second argument togsub. The function will receive an array with the matched text (index 0) and any capture group values (index 1 to N.)

			

String templates

As you increase the amount of JavaScript code in your applications, increasingly you'll find yourself with collections of objects of the same type and that you need to list or present in a formatted way.
It's not rare to find code in your applications that loops through a list of objects, building a string based on the object properties and some fixed formatting elements. Prototype.js comes with the Template class, which aims at helping you with exactly this type of scenarios.
The example below shows how to format a list of items in a shopping cart in multiple HTML lines.

			
For a more complete list of new methods, see the String extensions reference.

The Ajax object

The utility functions mentioned above are nice but, let's face it, they are not the most advanced type of thing, now are they? You could probably have done it yourself and you may even have similar functions in your own scripts. But those functions are just the tip of the iceberg.
I'm sure that your interest in prototype.js is driven mostly by its AJAX capabilities. So let's explain how the library makes your life easier when you need to perform AJAX logic.
The Ajax object is a pre-defined object, created by the library to wrap and simplify the tricky code that is involved when writing AJAX functionality. This object contains a number of classes that provide encapsulated AJAX logic. Let's take a look at some of them.

Using the Ajax.Request class

If you are not using any helper library, you are probably writing a whole lot of code to create a XMLHttpRequest object and then track its progress asynchronously, then extract the response and process it. And consider yourself lucky if you do not have to support more than one type of browser.
To assist with AJAX functionality, the library defines the Ajax.Request class.
Let's say you have an application that can communicate with the server via the url http://yourserver/app/get_sales?empID=1234&year=1998, which returns an XML response like the following.
 

	
		
			
				1234 
				1998-01 
				$8,115.36 
			
			
				1234 
				1998-02 
				$11,147.51 
			
		
	
			
			
Talking to the server to retrieve this XML is pretty simple using an Ajax.Request object. The sample below shows how it can be done.






			
Can you see the second parameter passed to the constructor of the Ajax.Request object? The parameter {method: 'get', parameters: pars, onComplete: showResponse} represents an anonymous object in literal notation (a.k.a. JSON). What it means is that we are passing an object that has a property named method that contains the string 'get', another property named parameters that contains the querystring of the HTTP request, and anonComplete property/method containing the function showResponse.
There are a few other properties that you can define and populate in this object, like asynchronous, which can be true or false and determines if the AJAX call to the server will be made asynchronously (the default value is true.)
This parameter defines the options for the AJAX call. In our sample, we are calling the url in the first argument via a HTTP GET command, passing the querystring contained in the variable pars, and the Ajax.Request object will call the showResponse function when it finishes retrieving the response.
As you may know, the XMLHttpRequest reports progress during the HTTP call. This progress can inform four different stages: LoadingLoadedInteractive, or Complete. You can make the Ajax.Request object call a custom function in any of these stages, the Complete being the most common one. To inform the function to the object, simply provide property/methods named onXXXXX in the request options, just like the onComplete from our example. The function you pass in will be called by the object with two arguments, the first one will be the XMLHttpRequest (a.k.a. XHR) object itself and the second one will be the evaluated X-JSON response HTTP header (if one is present). You can then use the XHR to get the returned data and maybe check thestatus property, which will contain the HTTP result code of the call. The X-JSON header is useful if you want to return some script or JSON-formatted data.
Two other interesting options can be used to process the results. We can specify the onSuccess option as a function to be called when the AJAX call executes without errors and, conversely, the onFailure option can be a function to be called when a server error happens. Just like the onXXXXX option functions, these two will also be called passing the XHR that carried the AJAX call and the evaluated X-JSON header.
Our sample did not process the XML response in any interesting way. We just dumped the XML in the textarea. A typical usage of the response would probably find the desired information inside the XML and update some page elements, or maybe even some sort of XSLT transformation to produce HTML in the page.
There's also another form of event callback handling available. If you have code that should always be executed for a particular event, regardless of which AJAX call caused it to happen, then you can use the new Ajax.Responders object.
Let's suppose you want to show some visual indication that an AJAX call is in progress, like a spinning icon or something of that nature. You can use two global event handlers to help you, one to show the icon when the first call starts and another one to hide the icon when the last one finishes. See example below.


Loading...
For more complete explanations, see the Ajax.Request reference and the options reference.

Using the Ajax.Updater class

If you have a server endpoint that can return information already formatted in HTML, the library makes life even easier for you with the Ajax.Updaterclass. With it you just inform which element should be filled with the HTML returned from the AJAX call. An example speaks better than I can write.



As you can see, the code is very similar to the previous example, with the exclusion of the onComplete function and the element id being passed in the constructor. Let's change the code a little bit to illustrate how it is possible to handle server errors on the client.
We will add more options to the call, specifying a function to capture error conditions. This is done using the onFailure option. We will also specify that the placeholder only gets populated in case of a successful operation. To achieve this we will change the first parameter from a simple element id to an object with two properties, success (to be used when everything goes OK) and failure (to be used when things go bad.) We will not be using thefailure property in our example, just the reportError function in the onFailure option.



If your server logic returns JavaScript code along with HTML markup, the Ajax.Updater object can evaluate that JavaScript code. To get the object to treat the response as JavaScript, you simply add evalScripts: true; to the list of properties in the last argument of the object constructor. But there's a caveat. Those script blocks will not be added to the page's script. As the option name evalScripts suggests, the scripts will be evaluated. What's the difference, you may ask? Lets assume the requested URL returns something like this:



			
In case you've tried it before, you know it doesn't work. The reason is that the script block will be evaluated, and evaluating a script like the above will not create a function named sayHi. It will do nothing. To create this function we need to change our script to create the function. See below.



			
Note that in the previous example we did not use the var keyword to declare the variable. Doing so would have created a function object that would be local to the script block (at least in IE). Without the var keyword the function object is scoped to the window, which is our intent.
For more complete explanations, see the Ajax.Updater reference and the options reference.

What are all those "?" and squares?

So you went and wrote some quick test scripts to update your pages using the Ajax.Updater object and it all worked fine. Life was good until you ran your scripts against real data. All of a sudden the updated text was displayed with question marks or unprintable character symbols where the non-English characters should be.
Your first suspect is prototype.js, Of course, it seemed too easy to be true. But don't blame the library just yet. Ask yourself how much you really understand character encoding, code pages, and how the browser deals with it. If you have a positive answer then I bet you are on your way to fix the problem. If you are among the other 80% (another useless, imprecise author's estimate) of web developers that take character encoding for granted, keep reading.
I won't pretend to be an authority on the topic, much less give you a complete explanation of how this is best handled. Instead you go straight to the solution that I use and provide hints on how this could be fixed in your own scenario.
Simply put, the solution revolves around the following statement: Serve what the browser is expecting you to serve. If we are going to update the page with text that contains Unicode/UTF-8 characters then we better make the browser aware of that.
Let's start with the simple case when you are just updating the page with text from a static HTML file that resides on your server. When you created that file, depending on which text editor you employed, it is very possible that the file was saved in ANSI (or better said, non-Unicode) format. This is the default for many text editors, especially source code editors, because the file size will be smaller and it's rather unusual to edit source code with Unicode characters in it.
Suppose you have the following file named static-content.html on your server. You saved this file saved in ANSI format.
Hi there, José. Yo no hablo español.
Your main page updates itself using something like the snippet below.

(this will be replaced)
When you click the button the static file is retrieved but the non-English characters are replaced by question marks or some other symbol. The displayed text will look similar to "Hi there, Jos?. Yo no hablo espa?ol." or "Hi there, Jos?Yo no hablo espa?", depending on your browser.
In this case, the solution is straightforward, simply save the static file in an appropriate format. Let's save it in UTF-8 and run the script again (any decent text editor will have an option in the Save As dialog.) You should now see the correct text (if not, your browser may have cached the old version, try using a different file name.)
If the HTML that you are serving is not static, if it is being dynamically generated by some application framework (like ASP.NET, PHP, or even Perl,) make sure the code that generates this HTML is producing the text in the appropriate encoding and code page, and include in the HTTP response headers one header that informs this. Each platform has a different way to achieve this, but they are very similar.
For example, in ASP.NET you can set this globally in your web.config file and the default configuration is good enough to avoid this problem in the first place. You should already have the following section in your web.config.
In classic ASP 3.0 you can fix this problem using the following code.
Response.CodePage = 65001
Response.CharSet = "utf-8" 
In PHP the syntax to add the response header looks like this.
In any case, your ultimate goal is to have the following HTTP header sent with your response.
Content-Type: text/html; charset=utf-8 
We used UTF-8 in our examples above, but if you need a different setting you can easily change.

Enumerating... Wow! Damn! Wahoo!

We are all familiar with for loops. You know, create yourself an array, populate it with elements of the same kind, create a loop control structure (for, foreach, while, repeat, etc,) access each element sequentially, by its numeric index, and do something with the element.
When you come to think about it, almost every time you have an array in your code it means that you'll be using that array in a loop sooner or later. Wouldn't it be nice if the array objects had more functionality to deal with these iterations? Yes, it would, and many programming languages provide such functionality in their arrays or equivalent structures (like collections and lists.)
Well, it turns out that prototype.js gives us the Enumerable object, which implements a plethora of tricks for us to use when dealing with iterable data. The prototype.js library goes one step further and extends the Array class with all the methods of Enumerable.

Loops, Ruby-style

In standard javascript, if you wanted to sequentially display the elements of an array, you could very well write something like this.


 
			
With our new best friend, prototype.js, we can rewrite this loop like this.

	function showList(){
		var simpsons = ['Homer', 'Marge', 'Lisa', 'Bart', 'Maggie'];
		simpsons.each( function(familyMember){
			alert(familyMember);
		});
	}
			
You are probably thinking "big freaking deal...just a weird syntax for the same old thing." Well, in the above example, yes, there's nothing too earth shattering going on. After all, there's not much to be changed in such a drop-dead-simple example. But keep reading, nonetheless.
Before we move on. Do you see this function that is being passed as an argument to the each method? Let's start referring to it as an iterator function.

Your arrays on steroids

Like we mentioned above, it's very common for all the elements in your array to be of the same kind, with the same properties and methods. Let's see how we can take advantage of iterator functions with our new souped-up arrays.
Here's how to find an element according to criteria.




 
			
Now let's kick it up another notch. See how we can filter out items in arrays, and then retrieve just a desired member from each element.

This text has a lot of links. Some are external and some are local
It takes just a little bit of practice to get completely addicted to this syntax. Take a look at the Enumerable and Array references for all the available functions.

Books I strongly recommend

Some books are just too good not to pass the word forward. The following books have helped me a lot learning the new skills required to adequately create AJAX applications and also consolidate the skills I though I already mastered. I think a good book is money well-spent, that keep paying for itself for a long time.
    

Reference for prototype.js

Extensions to the JavaScript classes

One of the ways the prototype.js library adds functionality is by extending the existing JavaScript classes.

Extensions for the Object class

MethodKindArgumentsDescription
extend(destination, source)staticdestination: any object, source: any objectProvides a way to implement inheritance by copying all properties and methods from source todestination.
inspect(targetObj)statictargetObj: any objectReturns a human-readable string representation of targetObj. It defaults to the return value oftoString if the given object does not define an inspect instance method.
keys(targetObj)statictargetObj: any objectReturns an Array with the names of all the properties and methods of given object.
values(targetObj)statictargetObj: any objectReturns a Array with the values of all the properties and methods of given object.
clone(targetObj)statictargetObj: any objectReturns a shallow copy of targetObj.

Extensions for the Number class

MethodKindArgumentsDescription
toColorPart()instance(none)Returns the hexadecimal representation of the number. Useful when converting the RGB components of a color into its HTML/CSS representation.
succ()instance(none)Returns the next number. This function is used in scenarios that involve iterations.
times(iterator)instanceiterator: a function object conforming to Function(index)Calls the iterator function repeatedly passing the current index in the indexargument.
The following sample will display alert message boxes from 0 to 9.



			

Extensions for the Function class

MethodKindArgumentsDescription
bind(object [, arg1 [, arg2 [...]]])instanceobject: the object that owns the methodReturns an instance of the function pre-bound to the function(=method) owner object. The returned function will use the same arguments as the original one (arg1, arg2, ... etc).
bindAsEventListener(object [, arg1 [, arg2 [...]]])instanceobject: the object that owns the methodReturns an instance of the function pre-bound to the function(=method) owner object. The returned function will have the current event object as its first argument followed optionally any other arguments passed after the object argument.
Let's see one of these extensions in action.
 Test?


			

Extensions for the String class

MethodKindArgumentsDescription
camelize()instance(none)Converts a hyphen-delimited-string into a camelCaseString. This function is useful when writing code that deals with style properties, for example.
capitalize()instance(none)Converts the first character to upper case.
dasherize()instance(none)Replaces underscores '_' with dashes '-'.
escapeHTML()instance(none)Returns the string with any HTML markup characters properly escaped
evalScripts()instance(none)Evaluates each 

Extensions for the document DOM object

MethodKindArgumentsDescription
getElementsByClassName(className [, parentElement])instanceclassName: name of a CSS class associated with the elements, parentElement: object or id of the element that contains the elements being retrieved.Returns all the elements that are associated with the given CSS class name. If noparentElement id given, the entire document body will be searched.

Extensions for the Event object

PropertyTypeDescription
KEY_BACKSPACENumber8: Constant. Code for the Backspace key.
KEY_TABNumber9: Constant. Code for the Tab key.
KEY_RETURNNumber13: Constant. Code for the Return key.
KEY_ESCNumber27: Constant. Code for the Esc key.
KEY_LEFTNumber37: Constant. Code for the Left arrow key.
KEY_UPNumber38: Constant. Code for the Up arrow key.
KEY_RIGHTNumber39: Constant. Code for the Right arrow key.
KEY_DOWNNumber40: Constant. Code for the Down arrow key.
KEY_DELETENumber46: Constant. Code for the Delete key.
observers:ArrayList of cached observers. Part of the internal implementation details of the object.
MethodKindArgumentsDescription
element(event)staticevent: an Event objectReturns element that originated the event.
isLeftClick(event)staticevent: an Event objectReturns true if the left mouse button was clicked.
pointerX(event)staticevent: an Event objectReturns the x coordinate of the mouse pointer on the page.
pointerY(event)staticevent: an Event objectReturns the y coordinate of the mouse pointer on the page.
stop(event)staticevent: an Event objectUse this function to abort the default behavior of an event and to suspend its propagation.
findElement(event, tagName)staticevent: an Event object, tagName: name of the desired tag.Traverses the DOM tree upwards, searching for the first element with the given tag name, starting from the element that originated the event.
observe(element, name, observer, useCapture)staticelement: object or id, name: event name (like 'click', 'load', etc), observer: function(evt) to handle the event, useCapture: if true, handles the event in the capture phase and if falsein the bubbling phase.Adds an event handler function to an event.
stopObserving(element, name, observer, useCapture)staticelement: object or id, name: event name (like 'click'), observer: function that is handling the event, useCapture: if true handles the event in the capture phase and if false in the bubbling phase.Removes an event handler from the event.
_observeAndCache(element, name, observer, useCapture)static Private method, do not worry about it.
unloadCache()static(none)Private method, do not worry about it. Clears all cached observers from memory.
Let's see how to use this object to add an event handler to the load event of the window object.
	
...
First
Second
Third

New objects and classes defined by prototype.js

Another way the library helps you is by providing many objects that implement both support for object oriented designs and common functionality in general.

The PeriodicalExecuter object

This object provides the logic for calling a given function repeatedly, at a given interval, using a timer.
MethodKindArgumentsDescription
[ctor](callback, interval)constructorcallback: a function that will be passed thePeriodcalExecuter object itself as the only argument, interval: number of secondsCreates one instance of this object that will call the function repeatedly.
registerCallback()instance(none)Resets the timer.
stop()instance(none)Cancels the timer, avoiding the execution of the callback.
onTimerEvent()instance(none)This method is what will be called by the timer. It, in turn, will invoke the callback method passing the object itself.
PropertyTypeDescription
callbackFunction(objExecuter)The function to be called. objExecuter: the PeriodcalExecuter making the call.
timerTimerA handle to the underlying timer object responsible for repeatedly invoking the callback method
frequencyNumberThis is actually the interval in seconds
currentlyExecutingBooleanIndicates if the callback is underway.

The Prototype object

The Prototype object does not have any important role, other than declaring the version of the library being used.
PropertyTypeDescription
VersionStringThe version of the library
emptyFunctionFunction()An empty function object
KFunction(obj)A function object that just echoes back the given parameter.
ScriptFragmentStringA regular expression to identify scripts

The Enumerable object

The Enumerable object allows one to write more elegant code to iterate items in a list-like structure.
Many other objects extend the Enumerable object to leverage its useful interface.
MethodKindArgumentsDescription
each(iterator)instanceiterator: a function object conforming to Function(value, index)Calls the given iterator function passing each element in the list in the first argument and the index of the element in the second argument
all([iterator])instanceiterator: a function object conforming to Function(value, index), optional.This function is a way to test the entire collection of values using a given function. allwill return true only if the iterator function returns a value that resolves to true for allthe elements. It will return false otherwise. If no iterator is given, then the test will be if the element itself resolves to true. You can simply read it as "check if all elements pass the test."
any([iterator])instanceiterator: a function object conforming to Function(value, index), optional.This function is a way to test the entire collection of values using a given function. anywill return true if the iterator function returns a value that resolves to true for at least one of the elements. It will return false otherwise. If no iterator is given, then the test will be if the element itself resolves to true. You can simply read it as "check if anyelement passes the test."
collect(iterator)instanceiterator: a function object conforming to Function(value, index)Calls the iterator function for each element in the collection and returns each result in anArray, one result element for each element in the collection, in the same sequence.
detect(iterator)instanceiterator: a function object conforming to Function(value, index)Calls the iterator function for each element in the collection and returns the first element that caused the iterator function to return true (or, more precisely, not-false.) If no element returns true, then detect returns null.
entries()instance(none)Same as toArray().
find(iterator)instanceiterator: a function object conforming to Function(value, index)Same as detect().
findAll(iterator)instanceiterator: a function object conforming to Function(value, index)Calls the iterator function for each element in the collection and returns an Array with all the elements that caused the iterator function to return a value that resolves to true. This function is the opposite of reject().
grep(pattern [, iterator])instancepattern: a RegExp object used to match the elements, iterator: a function object conforming to Function(value, index)Tests the string value of each element in the collection against the pattern regular expression . The function will return an Array containing all the elements that matched the regular expression. If the iterator function is given, then the Array will contain the result of calling the iterator with each element that was a match.
include(obj)instanceobj: any objectTries to find the given object in the collection. Returns true if the object is found, falseotherwise.
inGroupsOf(number, fillWith)instancenumber: number of items per group, fillWith: value used to fill empty spotsReturns the collection broken in groups containing as many items as specified by the first argument. If the quantity of items in the initial collection is not divisible by the number in the first argument, the resulting empty items at the end of the last group will be filled with null or with the value of the second argument, if provided. Quick example:['a','b','c','d'].inGroupsOf(3,'?') creates [ ['a','b','c'] , ['d','?','?'] ]
inject(initialValue, iterator)instanceinitialValue: any object to be used as the initial value, iterator: a function object conforming to Function(accumulator, value, index)Combines all the elements of the collection using the iterator function. The iterator is called passing the result of the previous iteration in the accumulator argument. The first iteration gets initialValue in the accumulator argument. The last result is the final return value.
invoke(methodName [, arg1 [, arg2 [...]]])instancemethodName: name of the method that will be called in each element, arg1..argN: arguments that will be passed in the method invocation.Calls the method specified by methodName in each element of the collection, passing any given arguments (arg1 to argN), and returns the results in an Array object.
map(iterator)instanceiterator: a function object conforming to Function(value, index)Same as collect().
max([iterator])instanceiterator: a function object conforming to Function(value, index)Returns the element with the greatest value in the collection or the greatest result of calling the iterator for each element in the collection, if an iterator is given.
member(obj)instanceobj: any objectSame as include().
min([iterator])instanceiterator: a function object conforming to Function(value, index)Returns the element with the lowest value in the collection or the lowest result of calling the iterator for each element in the collection, if an iterator is given.
partition([iterator])instanceiterator: a function object conforming to Function(value, index)Returns an Array containing two other arrays. The first array will contain all the elements that caused the iterator function to return true and the second array will contain the remaining elements. If the iterator is not given, then the first array will contain the elements that resolve to true and the other array will contain the remaining elements.
pluck(propertyName)instancepropertyName name of the property that will be read from each element. This can also contain the index of the elementRetrieves the value to the property specified by propertyName in each element of the collection and returns the results in an Array object.
reject(iterator)instanceiterator: a function object conforming to Function(value, index)Calls the iterator function for each element in the collection and returns an Array with all the elements that caused the iterator function to return a value that resolves to false. This function is the opposite of findAll().
select(iterator)instanceiterator: a function object conforming to Function(value, index)Same as findAll().
sortBy(iterator)instanceiterator: a function object conforming to Function(value, index)Returns an Array with all the elements sorted according to the result the iterator function call.
toArray()instance(none)Returns an Array with all the elements of the collection.
zip(collection1[, collection2 [, ... collectionN [,transform]]])instancecollection1 .. collectionN: enumerations that will be merged, transform: a function object conforming to Function(value, index)Merges each given collection with the current collection. The merge operation returns a new array with the same number of elements as the current collection and each element is an array (let's call them sub-arrays) of the elements with the same index from each of the merged collections. If the transform function is given, then each sub-array will be transformed by this function before being returned. Quick example: [1,2,3].zip([4,5,6], [7,8,9]).inspect() returns "[ [1,4,7],[2,5,8],[3,6,9] ]"

The Hash object

The Hash object implements a hash structure, i.e. a collection of Key:Value pairs.
Each item in a Hash object is an array with two elements: first the key then the value. Each item also has two properties: key and value, which are pretty self-explanatory.
MethodKindArgumentsDescription
keys()instance(none)Returns an Array with the keys of all items.
values()instance(none)Returns an Array with the values of all items.
merge(otherHash)instanceotherHash: Hash objectCombines the hash with the other hash passed in and returns the new resulting hash.
toQueryString()instance(none)Returns all the items of the hash in a string formatted like a query string, e.g.'key1=value1&key2=value2&key3=value3'
inspect()instance(none)Overridden to return a nicely formatted string representation of the hash with its key:value pairs.

The ObjectRange class

Inherits from Enumerable
Represents a range of values, with upper and lower bounds.
PropertyTypeKindDescription
start(any)instanceThe lower bound of the range
end(any)instanceThe upper bound of the range
exclusiveBooleaninstanceDetermines if the boundaries themselves are part of the range.
MethodKindArgumentsDescription
[ctor](start, end, exclusive)constructorstart: the lower bound, end: the upper bound, exclusive: include the bounds in the range?Creates one range object, spanning from start to end. It is important to note that start and end have to be objects of the same type and they must have a succ() method.
include(searchedValue)instancesearchedValue: value that we are looking forChecks if the given value is part of the range. Returns true or false.

The Class object

The Class object is used when declaring the other classes in the library. Using this object when declaring a class causes the to new class to support aninitialize() method, which serves as the constructor.
See the sample below.
//declaring the class
var MySampleClass = Class.create();

//defining the rest of the class implementation
MySampleClass.prototype = {

   initialize: function(message) {
		this.message = message;
   },

   showMessage: function(ajaxResponse) {
      alert(this.message);
   }
};	

//now, let's instantiate and use one object
var myTalker = new MySampleClass('hi there.');
myTalker.showMessage(); //displays alert

			
MethodKindArgumentsDescription
create(*)instance(any)Defines a constructor for a new class

The Ajax object

This object serves as the root and namespace for many other classes that provide AJAX functionality.
PropertyTypeKindDescription
activeRequestCountNumberinstanceThe number of AJAX requests in progress.
MethodKindArgumentsDescription
getTransport()instance(none)Returns a new XMLHttpRequest object

The Ajax.Responders object

Inherits from Enumerable
This object maintains a list of objects that will be called when Ajax-related events occur. You can use this object, for example, if you want to hook up a global exception handler for AJAX operations.
PropertyTypeKindDescription
respondersArrayinstanceThe list of objects registered for AJAX events notifications.
MethodKindArgumentsDescription
register(responderToAdd)instanceresponderToAdd: object with methods that will be called.The object passed in the responderToAdd argument should contain methods named like the AJAX events (e.g. onCreate,onCompleteonException, etc.) When the corresponding event occurs all the registered objects that contain a method with the appropriate name will have that method called.
unregister(responderToRemove)instanceresponderToRemove: object to be removed from the list.The object passed in the responderToRemove argument will be removed from the list of registered objects.
dispatch(callback, request, transport, json)instancecallback: name of the AJAX event being reported, request: the Ajax.Request object responsible for the event, transport: the XMLHttpRequest object that carried (or is carrying) the AJAX call, json: the X-JSON header of the response (if present)Runs through the list of registered objects looking for the ones that have the method determined in the callback argument. Then each of these methods is called passing the other 3 arguments. If the AJAX response contains a X-JSON HTTP header with some JSON content, then it will be evaluated and passed in the json argument. If the event is onException, the transport argument will have the exception instead and json will not be passed.

The Ajax.Base class

This class is used as the base class for most of the other classes defined in the Ajax object.
MethodKindArgumentsDescription
setOptions(options)instanceoptions: AJAX optionsSets the desired options for the AJAX operation
responseIsSuccess()instance(none)Returns true if the AJAX operation succeeded, false otherwise
responseIsFailure()instance(none)The opposite of responseIsSuccess().

The Ajax.Request class

Inherits from Ajax.Base
Encapsulates AJAX operations
PropertyTypeKindDescription
EventsArraystaticList of possible events/statuses reported during an AJAX operation. The list contains: 'Uninitialized', 'Loading', 'Loaded', 'Interactive', and 'Complete.'
transportXMLHttpRequestinstanceThe XMLHttpRequest object that carries the AJAX operation
urlStringinstanceThe URL targeted by the request.
MethodKindArgumentsDescription
[ctor](url, options)constructorurl: the url to be fetched, options: AJAX optionsCreates one instance of this object that will call the given url using the given options. The onCreate event will be raised during the constructor call. Important: It is worth noting that the chosen url is subject to the browser's security settings. In many cases the browser will not fetch the url if it is not from the same host (domain) as the current page. You should ideally use only local urls to avoid having to configure or restrict the user's browser. (Thanks Clay).
evalJSON()instance(none)This method is typically not called externally. It is called internally to evaluate the content of an eventual X-JSON HTTP header present in the AJAX response.
evalResponse()instance(none)This method is typically not called externally. If the AJAX response has a Content-typeheader of text/javascript then the response body will be evaluated and this method will be used.
header(name)instancename: HTTP header nameRetrieves the contents of any HTTP header of the AJAX response. Call this only after the AJAX call is completed.
onStateChange()instance(none)This method is typically not called externally. It is called by the object itself when the AJAX call status changes.
request(url)instanceurl: url for the AJAX callThis method is typically not called externally. It is already called during the constructor call.
respondToReadyState(readyState)instancereadyState: state number (1 to 4)This method is typically not called externally. It is called by the object itself when the AJAX call status changes.
setRequestHeaders()instance(none)This method is typically not called externally. It is called by the object itself to assemble the HTTP header that will be sent during the HTTP request.

The options argument object

An important part of the AJAX operations is the options argument. There's no options class per se. Any object can be passed, as long as it has the expected properties. It is common to create anonymous objects just for the AJAX calls.
PropertyTypeDefaultDescription
methodString'post'Method of the HTTP request
parametersString or Object''The url-formatted list of values passed to the request (for example'employee=john&month=11') or a hash-like object that represents the parameters (for example {employee:'john', month:11}.)
asynchronousBooleantrueIndicates if the AJAX call will be made asynchronously
postBodyStringundefinedContent passed to in the request's body in case of a HTTP POST
requestHeadersArrayundefinedList of HTTP headers to be passed with the request. This list must have an even number of items, any odd item is the name of a custom header, and the following even item is the string value of that header. Example:['my-header1', 'this is the value', 'my-other-header', 'another value']
encodingString'UTF-8'The character encoding used in the body of a request (especially POST requests.) UTF-8should be enough in most cases, but if you know what you're doing, you can use a different encoding.
contentTypeString'application/x-www-form-urlencoded'Sets the Content-Type HTTP header of the Ajax request.
onXXXXXXXXFunction(XMLHttpRequest, Object)undefinedCustom function to be called when the respective event/status is reached during the AJAX call. There are several alternatives for the "XXXXXXXX" in this option, among the alternatives are the statuses in Ajax.Request.Events, and the HTTP status codes. Example var myOpts = {on403: notAllowed, onComplete: showResponse, onLoaded: registerLoaded};. The function used will receive one argument, containing theXMLHttpRequest object that is carrying the AJAX operation and another argument containing the evaluated X-JSON response HTTP header.
onSuccessFunction(XMLHttpRequest, Object)undefinedCustom function to be called when the AJAX call completes successfully. The function used will receive one argument, containing the XMLHttpRequest object that is carrying the AJAX operation and another argument containing the evaluated X-JSON response HTTP header.
onFailureFunction(XMLHttpRequest, Object)undefinedCustom function to be called when the AJAX call completes with error. The function used will receive one argument, containing the XMLHttpRequest object that is carrying the AJAX operation and another argument containing the evaluated X-JSON response HTTP header.
onExceptionFunction(Ajax.Request, exception)undefinedCustom function to be called when an exceptional condition happens on the client side of the AJAX call, like an invalid response or invalid arguments. The function used will receive two arguments, containing the Ajax.Request object that wraps the AJAX operation and the exception object.
insertionan Insertion classundefinedA class that will determine how the new content will be inserted. Applies only toAjax.Updater objects and if nothing is specified, the new content will completely replace the existing content. If an Insertion-derived class is given, the content will be added to the existing content. It can be Insertion.BeforeInsertion.TopInsertion.Bottom, or Insertion.After.
evalScriptsBooleanundefined, falseDetermines if script blocks will be evaluated when the response arrives. Applies only toAjax.Updater objects.
decayNumberundefined, 1Determines the progressive slowdown in a Ajax.PeriodicalUpdater object refresh rate when the received response is the same as the last one. For example, if you use 2, after one of the refreshes produces the same result as the previous one, the object will wait twice as much time for the next refresh. If it repeats again, the object will wait four times as much, and so on. Leave it undefined or use 1 to avoid the slowdown.
frequencyNumberundefined, 2Interval (not frequency) between refreshes, in seconds. Applies only toAjax.PeriodicalUpdater objects.

The Ajax.Updater class

Inherits from Ajax.Request
Used when the requested url returns HTML that you want to inject directly in a specific element of your page. You can also use this object when the url returns 
Will change the HTML to


Hello, Chief Wiggum. How's it going?	
			

The Insertion.Top class

Inherits from Abstract.Insertion
Inserts HTML as the first child under an element. The content will be right after the opening tag of the element.
MethodKindArgumentsDescription
[ctor](element, content)constructorelement: element object or id, content: HTML to be insertedInherited from Abstract.Insertion. Creates an object that will help with dynamic content insertion.
The following code

Hello, Wiggum. How's it going?


			
Will change the HTML to

Hello, Mr. Wiggum. How's it going?	
			

The Insertion.Bottom class

Inherits from Abstract.Insertion
Inserts HTML as the last child under an element. The content will be right before the element's closing tag.
MethodKindArgumentsDescription
[ctor](element, content)constructorelement: element object or id, content: HTML to be insertedInherited from Abstract.Insertion. Creates an object that will help with dynamic content insertion.
The following code

Hello, Wiggum. How's it going?


			
Will change the HTML to

Hello, Wiggum. How's it going? What's up?	
			

The Insertion.After class

Inherits from Abstract.Insertion
Inserts HTML right after the element's closing tag.
MethodKindArgumentsDescription
[ctor](element, content)constructorelement: element object or id, content: HTML to be insertedInherited from Abstract.Insertion. Creates an object that will help with dynamic content insertion.
The following code

Hello, Wiggum. How's it going?


			
Will change the HTML to

Hello, Wiggum. How's it going? Are you there?	
			

The Field object

This object provides some utility functions for working with input fields in forms. It's simply a shorthand to Form.Element.

The Form object

This object provides some utility functions for working with data entry forms and their input fields.
MethodKindArgumentsDescription
serialize(form)instanceform: form element object or idReturns a url-formatted list of field names and their values, like 'field1=value1&field2=value2&field3=value3'
findFirstElement(form)instanceform: form element object or idReturns the first enabled field element in the form.
getElements(form)instanceform: form element object or idReturns an Array containing all the input fields in the form.
getInputs(form [, typeName [, name]])instanceform: form element object or id, typeName: the type of the input element, name: the name of the input element.Returns an Array containing all the  elements in the form. Optionally, the list can be filtered by the type or nameattributes of the elements.
disable(form)instanceform: form element object or idDisables all the input fields in the form.
enable(form)instanceform: form element object or idEnables all the input fields in the form.
focusFirstElement(form)instanceform: form element object or idActivates the first visible, enabled input field in the form.
reset(form)instanceform: form element object or idResets the form. The same as calling the reset() method of the form object.

The Form.Element object

This object provides some utility functions for working with form elements. These functions have native DOM equivalents, but those don't return the element as the result of the function call, preventing the chaining of method calls.
The methods below are not the only methods in this object at runtime. All the methods from Form.Element.Methods will also be added to this object.
MethodKindArgumentsDescription
focus(element)instanceelement: element object or id of a form fieldMoves the input focus to the field.
select(element)instanceelement: element object or id of a form fieldSelects the value entered in the element.

The Form.Element.Methods object

This object provides some utility functions for working with form field elements, that will be copied over to any field element accessed via the functions $()and $$().
Similarly to the Element.Methods methods, when they are copied, the first argument is dropped and becomes the element itself. These methods are also copied to the Form.Element object so you don't typically use the methods from Form.Element.Methods directly, but rather via the Form.Elementobject for consistency.
MethodKindArgumentsDescription
activate(element)instanceelement: element object or idMoves the input focus to the field and selects its contents.
clear(element)instanceelement: element object or idEmpties the field.
disable(element)instanceelement: element object or idDisables the field or button, so it cannot be changed or clicked.
enable(element)instanceelement: element object or idEnables the field of button for being changed or clicked.
getValue(element)instanceelement: element object or idReturns the value of the element.
present(element)instanceelement: element object or idReturns true if the field is not empty.
serialize(element)instanceelement: element object or idReturns the element's name=value pair, like 'elementName=elementValue'

The Form.Element.Serializers object

This object provides some utility functions that are used internally in the library to assist extracting the current value of the form elements.
MethodKindArgumentsDescription
inputSelector(element)instanceelement: object or id of a form element that has the checked property, like a radio button or checkbox.Returns an Array with the element's name and value, like['elementName', 'elementValue']
textarea(element)instanceelement: object or id of a form element that has the value property, like a textbox, button or password field.Returns an Array with the element's name and value, like['elementName', 'elementValue']
select(element)instanceelement: object of a Returns an Array with the element's name and all selected options' values or texts, like ['elementName', 'selOpt1 selOpt4 selOpt9']

The Abstract.TimedObserver class

This class is used as the base class for the other classes that will monitor one element until its value (or whatever property the derived class defines) changes. This class is used like an abstract class.
Subclasses can be created to monitor things like the input value of an element, or one of the style properties, or number of rows in a table, or whatever else you may be interested in tracking changes to.
MethodKindArgumentsDescription
[ctor](element, frequency, callback)constructorelement: element object or id, frequency: interval in seconds, callback: function to be called when the element changesCreates an object that will monitor the element.
getValue()instance, abstract(none)Derived classes have to implement this method to determine what is the current value being monitored in the element.
registerCallback()instance(none)This method is typically not called externally. It is called by the object itself to start monitoring the element.
onTimerEvent()instance(none)This method is typically not called externally. It is called by the object itself periodically to check the element.
PropertyTypeDescription
elementObjectThe element object that is being monitored.
frequencyNumberThis is actually the interval in seconds between checks.
callbackFunction(Object, String)The function to be called whenever the element changes. It will receive the element object and the new value.
lastValueStringThe last value verified in the element.

The Form.Element.Observer class

Inherits from Abstract.TimedObserver
Implementation of an Abstract.TimedObserver that monitors the value of form input elements. Use this class when you want to monitor an element that does not expose an event that reports the value changes. In that case you can use the Form.Element.EventObserver class instead.
MethodKindArgumentsDescription
[ctor](element, frequency, callback)constructorelement: element object or id, frequency: interval in seconds, callback: function to be called when the element changesInherited from Abstract.TimedObserver. Creates an object that will monitor the element's valueproperty.
getValue()instance(none)Returns the element's value.

The Form.Observer class

Inherits from Abstract.TimedObserver
Implementation of an Abstract.TimedObserver that monitors any changes to any data entry element's value in a form. Use this class when you want to monitor a form that contains a elements that do not expose an event that reports the value changes. In that case you can use the Form.EventObserverclass instead.
MethodKindArgumentsDescription
[ctor](form, frequency, callback)constructorform: form object or id, frequency: interval in seconds, callback function to be called when any data entry element in the form changesInherited from Abstract.TimedObserver. Creates an object that will monitor the form for changes.
getValue()instance(none)Returns the serialization of all form's data.

The Abstract.EventObserver class

This class is used as the base class for the other classes that execute a callback function whenever a value-changing event happens for an element.
Multiple objects of type Abstract.EventObserver can be bound to the same element, without one wiping out the other. The callbacks will be executed in the order they are assigned to the element.
The triggering event is onclick for radio buttons and checkboxes, and onchange for textboxes in general and listboxes/dropdowns.
MethodKindArgumentsDescription
[ctor](element, callback)constructorelement: element object or id, callback: function to be called when the event happensCreates an object that will monitor the element.
getValue()instance, abstract(none)Derived classes have to implement this method to determine what is the current value being monitored in the element.
registerCallback()instance(none)This method is typically not called externally. It is called by the object to bind itself to the element's event.
registerFormCallbacks()instance(none)This method is typically not called externally. It is called by the object to bind itself to the events of each data entry element in the form.
onElementEvent()instance(none)This method is typically not called externally. It will be bound to the element's event.
PropertyTypeDescription
elementObjectThe element object that is being monitored.
callbackFunction(Object, String)The function to be called whenever the element changes. It will receive the element object and the new value.
lastValueStringThe last value verified in the element.

The Form.Element.EventObserver class

Inherits from Abstract.EventObserver
Implementation of an Abstract.EventObserver that executes a callback function to the appropriate event of the form data entry element to detect value changes in the element. If the element does not expose any event that reports changes, then you can use the Form.Element.Observer class instead.
MethodKindArgumentsDescription
[ctor](element, callback)constructorelement: element object or id, callback: function to be called when the event happensInherited from Abstract.EventObserver. Creates an object that will monitor the element's value property.
getValue()instance(none)Returns the element's value

The Form.EventObserver class

Inherits from Abstract.EventObserver
Implementation of an Abstract.EventObserver that monitors any changes to any data entry element contained in a form, using the elements' events to detect when the value changes. If the form contains elements that do not expose any event that reports changes, then you can use the Form.Observerclass instead.
MethodKindArgumentsDescription
[ctor](form, callback)constructorform: form object or id, callback: function to be called when any data entry element in the form changesInherited from Abstract.EventObserver. Creates an object that will monitor the form for changes.
getValue()instance(none)Returns the serialization of all form's data.

The Position object

This object provides a host of functions that help when working with element positioning.
MethodKindArgumentsDescription
absolutize(element)instanceelement: element object or idChanges the object postioning to absolute but takes care of not altering its current size and location on the page.
clone(source, target [, cloneOptions])instancesource: element object or id, target: element object or id, cloneOptions: allow fine tuning of the operationResizes and repositions the target element identically to the source element. Note that the target element will only be repositioned if it already has the position style attribute set to absolute , otherwise only the size will change. Check thecloneOptions reference below.
cumulativeOffset(element)instanceelement: objectReturns an Array with the total offsets of the element, including any of the element's ancestors offsets. The resulting array is similar to [total_left_offset, total_top_offset]
offsetParent(element)instanceelement: objectReturns the first non-statically-positioned ancestor of the element.
overlap(mode, element)instancemode: 'vertical' or 'horizontal', element: objectwithin() needs to be called right before calling this method. This method will return a decimal number between 0.0 and 1.0 representing the fraction of the coordinate that overlaps on the element. As an example, if the element is a square DIV with a 100px side and positioned at (300, 300), then within(divSquare, 330, 330); overlap('vertical', divSquare); should return 0.70, meaning that the point is at the 70% (100px - 30px = 70px) mark from the bottom border of the DIV. The easiest way to understand it is to think of the given coordinate pair as the top-left corner of another rectangle, overlapping the first one. The number will be the percentage of the width or height that is overlapped (assuming that the second rectangle is large enough.)
page(element)instanceelement: objectReturns an Array with the coordinates of the element relative to the page. The resulting array is similar to [left, top]
positionedOffset(element)instanceelement: objectReturns an Array with the correct offsets of the element relative to its offset parent, in pixels. The resulting array is similar to [left_offset, top_offset]
prepare()instance(none)Adjusts the deltaX and deltaY properties to accommodate changes in the scroll position. Remember to call this method before any calls towithinIncludingScrolloffset after the page scrolls.
realOffset(element)instanceelement: objectReturns an Array with the correct scroll offsets of the element, including any scroll offsets that affect the element. The resulting array is similar to[total_scroll_left, total_scroll_top]
relativize(element)instanceelement: element object or idChanges the object postioning to relative but takes care of not altering its current size and location on the page. Works best with elements that have been absolutized previously.
within(element, x, y)instanceelement: object, x and y: coordinates of a pointTests if the given point coordinates are inside the bounding rectangle of the given element
withinIncludingScrolloffsets(element, x, y)instanceelement: object, x and y: coordinates of a point 

The cloneOptions argument object

The clone() method of the Position object takes an optional third argument, used to more detailedly control the cloning operation.
PropertyTypeDefaultDescription
offsetLeftNumber0Number of pixels to offset the target element from the left of the source.
offsetTopNumber0Number of pixels to offset the target element from the top of the source.
setHeightBooleantrueCauses the height of the source element to be copied over to the target element.
setLeftBooleantrueCauses the left position of the source element to be copied over to the target element.
setTopBooleantrueCauses the top position of the source element to be copied over to the target element.
setWidthBooleantrueCauses the width of the source element to be copied over to the target element.

No comments: