This document covers Prototype 1.4. There will be a free upgrade to the Prototype 1.5 version of this document.
Copyright © 2006 O’Reilly Media, Inc.
November 29, 2006
Abstract
This short cut provides a complete quick reference to the Prototype JavaScript framework. Prototype is an open-source library that is particularly useful to developers of dynamic Ajax applications, and to other web developers who need to work with DOM elements.
If you’re a web developer building sophisticated, user-friendly applications, you should be using Prototype. This reference gives you everything you need to use Prototype to its fullest.
The Prototype JavaScript framework by Sam Stephenson is designed to ease development of
dynamic web applications. It extends core JavaScript classes and adds new ones to provide
powerful features, especially for working with Ajax and manipulating DOM elements. In many
ways, it also bridges part of the gap between the JavaScript and Ruby languages—particularly
by borrowing ideas from Ruby’s Enumerable
module.
Prototype can be downloaded from its web site, http://prototype.conio.net/.
This chapter organizes Prototype’s functionality into three major sections: Ajax Support
(wrappers for the XMLHttpRequest
object enabling easy
two-way communication with remote servers), DOM Manipulation Support (a slew of methods for
interacting with page elements), and Core Extensions (convenient tools for working with
JavaScript data structures, through new classes and extensions of core classes).
All of the code examples in this chapter are JavaScript. But because so much of Prototype is designed to work with HTML and DOM objects, many examples also include some HTML markup at the beginning, formatted as a JavaScript comment:
// <p>Example Paragraph</p>
JavaScript comments are also used to denote the return value of methods. For example:
// => 'result'
Another example:
// <p id="one">One</p> $('one').innerHTML; // => 'One'
Here the first line indicates a snippet of HTML that will be used in the example, the second line demonstrates a Prototype method, and the third line indicates the value that the method returns.
And now, on with the show.
The Ajax
object serves as the root and namespace for
Prototype’s classes that provide Ajax functionality.
activeRequestCount
The number of Ajax requests in progress.
getTransport()
Returns a new XMLHttpRequest
object
Ajax.Base
is used as the base class for most of the
other classes defined in the Ajax
object.
setOptions(
options
)
Sets the desired options for the Ajax operation. See "Ajax.Request options,” later.
responseIsSuccess()
true
if the Ajax operation succeeded, and
false
otherwise.
responseIsFailure()
false
if the Ajax operation succeeded, and
true
otherwise.
The Ajax.Request
class (which inherits from Ajax.Base
) encapsulates Ajax operations.
initialize(
url,
options
)
Creates one instance of this object that will create an XMLHttpRequest
object for the given url
, using
the given options
(which may include callbacks to handle
the response; see Ajax.Request Options).
The onCreate
event will be raised during the
constructor call. Generally, only URLs from the same domain as the current page are
allowed to be retrieved.
request(
url
)
Called by the constructor; not typically called externally.
evalJSON()
Evaluates the content of an eventual X-JSON
HTTP header present in the Ajax response. Not typically called externally.
evalResponse()
Evaluates the response body as JavaScript. Called internally if the response has a
Content-type
header of text/javascript
. Not typically called externally.
header(
name
)
Retrieves the contents of the HTTP header named name
from the response (only available after the Ajax call is completed).
onStateChange()
Called internally when the readyState
changes. See the
table "XMLHttpRequest readyState
properties,” later, for a list of readyState
properties. Not typically called externally.
respondToReadyState(
readyState
)
Called by the object when the readyState
changes See
the table "XMLHttpRequest
readyState properties,” later, for a list of readyState
properties. Not typically called externally.
setRequestHeaders()
Assembles the HTTP header that will be sent during the HTTP request. Not typically called externally.
Events
An array of possible events/statuses reported during an Ajax operation. The list
contains: Uninitialized
, Loading
, Loaded
, Interactive
, and Complete
.
transport
The XMLHttpRequest
object that carries the Ajax
operation.
url
The URL targeted by the request.
The options
argument is an anonymous JavaScript object in
literal notation. Any object can be passed as long as it has the expected properties, but
it’s common to create anonymous objects just for the Ajax calls.
Property | Description |
---|---|
| A string with the HTTP method for the
request. Defaults to |
| A string with the URL-formatted list of values passed to the request. Defaults to empty. |
| A boolean indicating whether the Ajax call will be made asynchronously. Defaults to true. |
| A string with the content passed to in the
request’s body in case of a HTTP |
| An array 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. Defaults to undefined. Example: |
| Callback function to be called when the
request’s |
| Callback function to be called when the
request’s |
| Callback function to be called when the
request’s |
| Callback function to be called when the
request’s |
| Callback function to be called when the
request’s |
| Callback function to be called when the
request’s |
| |
| Callback 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 will receive two arguments:
the |
Create an Ajax request for a remote file, with options to specify the HTTP request method, and a callback to handle the response:
new Ajax.Request('/data.html', { method: 'get', onComplete: showResponse }); // alert the returned value function showResponse(request) { alert(request.responseText); }
The callback could also be defined inline. For example, this is equivalent to the previous example:
new Ajax.Request(' /data.xml', { method: 'get', onComplete: function(request){ alert(request.responseText); } });
Table 1. XMLHttpRequest readyState properties
readyState | Description | Prototype callback |
---|---|---|
Request object has not yet been created. | ||
0 (Uninitialized) | Request object’s | |
1 (Loading) | Request object’s |
|
2 (Loaded) | The request has been initiated. |
|
3 (Interactive) | The response is being received. |
|
The response is ready and its status is in the 200 range. |
| |
The response is ready and its status is not in the 200 range. |
| |
4 (Complete) | The response is ready. |
|
The Ajax.Updater
class (which inherits from Ajax.Request
) is used when the requested URL returns content
that you want to inject directly in a specific element of your page.
initialize(
container, url,
options
)
Creates an Ajax.Updater
instance that will call
url
using the given options
.
The container
argument can be the id of an element, the
element object itself, or an object with either or both of two properties: success
, which is an element or id that will be updated
when the Ajax call succeeds, and failure
, which is
the element (or id) that will be updated otherwise. The options
argument provides the same options as Ajax.Request
(see "Ajax.Request options,” earlier) and
some options particular to updaters (see "Ajax.Updater options,” later).
updateContent()
Called internally when the response is received. It will update the appropriate
element with the HTML or call the function passed in the insertion
option. The function will be called with two arguments: the
element to be updated and the response text. Not typically called externally.
Contains two properties: success
, which is the
element to be updated when the request succeeds, and failure
, which is the element to be updated otherwise.
In addition to the options described in the section "Ajax.Request options,” Ajax.Updater
classes can also take these options:
| An |
| A boolean that determines whether |
Replace the contents of a DIV
with the contents of
a remote file:
// <div id="target">(To be replaced)</div> new Ajax.Updater('target', '/data.html', {method: 'get'});
This next example is the same as above, but it updates the element only if the request was successful, and alerts the user if not:
// <div id="target"></div> new Ajax.Updater({success: 'target'}, '/data.html', { method: 'get', onFailure: function(request) { alert('Sorry. There was an error.') } });
The Ajax.PeriodicalUpdater
class repeatedly
instantiates and uses an Ajax.Updater
object to refresh
an element on the page, or to perform any of the other tasks the Ajax.Updater
can perform.
initialize(
container, url,
options
)
Creates an instance that will update container
with the
result of a request to url
.
container
can be the id of an element, the element object
itself, or an object with one or both of two properties: success
, which is an element (or id) that will be updated when the
request succeeds, and failure
, which is an element
(or id) that will be updated otherwise. The available properties of the options
argument are detailed in the section "Ajax.PeriodicalUpdater options.”
start()
Start performing the periodical tasks. Not typically called externally.
stop()
Stop performing the periodical tasks. After stopping, the object will call the
callback given in the onComplete
option (if
any).
updateComplete()
Schedules the next refresh; called by the currently used Ajax.Updater
after it completes the request. Not typically called
externally.
onTimerEvent()
Called internally when it is time for the next update. Not typically called externally.
container
An object that will be passed straight to the Ajax.Updater
’s constructor.
url
A string that will be passed straight to the Ajax.Updater
’s constructor.
frequency
Interval (not frequency) between refreshes, in seconds. Defaults to 2 seconds.
This number will be multiplied by the current decay
when invoking the Ajax.Updater
object
decay
A number that keeps the current decay level applied when re-executing the task.
updater
The most recently used Ajax.Updater
object.
timer
The JavaScript timer being used to notify the object when it is time for the next refresh.
In addition to the options described in the sections "Ajex.Request options" and "Ajax.Updater options,” Ajax.PeriodicalUpdater
can also take these options:
| A number determining the progressive slowdown
in an |
| Interval (not frequency) between refreshes,
in seconds. Applies only to |
The Ajax.Responders
object maintains a list of
callbacks that will be called when Ajax-related events occur, regardless of what object
created them; for example, creating a global exception handler for Ajax operations. 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 Ajax.Responders
object.
register(
responderToAdd
)
The object passed in the responderToAdd
argument should
contain methods named like the Ajax events (e.g., onCreate
, onComplete
, onException
). When the corresponding event occurs, all the
registered objects that contain a method with the appropriate name will have that
method called.
unregister(
responderToRemove
)
The object passed in the responderToRemove
argument
will be removed from the list of registered objects.
dispatch(
callback, request,
transport, json
)
Runs through the list of registered objects looking for the ones that have the
method determined in callback
. Then each of these methods
is called passing request
,
transport
, and json
. If the
Ajax response contains an 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.
responders
An array of objects registered for Ajax events notifications.
In addition to the methods listed here, Ajax.Responders
is also extended by the Enumerable methods.
Suppose you want to show some visual indication that an Ajax call is in progress, like a spinning icon. 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:
// <img src="spinner.gif" id="spinner" style="display: none"> Ajax.Responders.register({ onCreate: function(){ $('spinner').show(); }, onComplete: function() { if(Ajax.activeRequestCount == 0) $('spinner').hide(); } });
If you encounter odd characters—like question marks and squares where letters should be—the problem is character encoding. The solution is simple: serve what the browser is expecting you to serve. To update a page with text that contains Unicode characters, you have to tell the browser what format it is.
For example, suppose you have the following file named static.html on your server, saved in ASCII format:
<div> Hi there, José. Yo no hablo español. </div>
Your main page then updates itself with Ajax.Updater
:
<div id='target'>(To be replaced)</div> <p><a href="#" onclick=" new Ajax.Updater('target', '/static.html', {method: 'get'}); return false;" >Update text</a></p>
When you click the link, the static file is retrieved, but the non-English characters are replaced by question marks or other symbols, like “Hi there, Jos?. Yo no hablo espa?ol.” In this case, the solution is straightforward: simply save the static file in an appropriate format, like UTF-8. Save it with the correct encoding and run the script again and you should see the correct text.
If the content you’re serving is dynamically generated by some application framework (like Rails), make sure the application generating the HTML uses the appropriate encoding and includes an HTTP response header to inform the browser of the encoding, such as:
Content-Type: text/html; charset=utf-8
The dollar function ($()
) is a
specialized wrapper to the standard document.getElementById()
DOM method. Like that method, $()
returns the element with the given id.
Unlike the DOM method, you can pass more than one argument and $()
will return an array with all the requested elements. And if an argument is
anything other than a string, it will be passed through directly. As a result, you can
safely call $()
on a value multiple times. Whether the
argument is a string or already a DOM element, the output will be the same. For
example:
// <p id="one">One</p> // <p id="two">Two</p> $('one').toString(); // => '[object HTMLParagraphElement]' $('one','two').toString(); // => [object P],[object P] $($('one')).toString(); // => [object HTMLParagraphElement]
Provides methods for manipulating elements in the DOM.
hide(
element
)
Hides element
by setting its style.display
to 'none'
.
show(
element
)
Shows element
by resetting its style.display
to ''
.
toggle(
element
)
Toggles the visibility of element
.
visible(
element
)
Returns a boolean value indicating if the element is visible.
remove(
element
)
Removes element
from the document.
update(
element
,
html
)
Replaces the inner html of element
with the
html
. If the html
contains
<script>
blocks they will not be included,
but they will be evaluated.
classNames(
element
)
Returns an Element.ClassNames
object
representing the CSS class names associated with
element
.
hasClassName(
element
,
className
)
Returns true
if
element
has className
as one
of its class names.
addClassName(
element
,
className
)
Adds className
to the list of CSS class names
associated with element
.
removeClassName(
element
,
className
)
Removes className
from the list of CSS class names
associated with element
.
getStyle(
element
,
cssProperty
)
Returns the value of the CSS property cssProperty
(in
either 'prop-name'
or 'propName'
format) in the element
or null
if not present.
setStyle(
element,
cssPropertyHash
)
Sets the value of the CSS properties in element
,
according to the values in the cssPropertyHash
hash.
getDimensions(
element
)
Returns the dimensions of element
. The returned value
is an object with two properties: height
and
width
.
getHeight(
element
)
Returns the offsetHeight
of
element
.
makeClipping(
element
)
undoClipping(
element
)
makePositioned(
element
)
Changes element
’s style.position
to relative
.
undoPositioned(
element
)
Clears the element
’s style.position
to ''
.
scrollTo(
element
)
Scrolls the window to element
’s position.
cleanWhitespace(
element
)
Removes any white space text node children of
element
.
empty(
element
)
Returns a boolean value indicating whether element
’s
tag is empty (or has only whitespaces).
Inherits from Enumerable. Represents the collection of CSS class names associated with an element.
initialize(
element
)
Creates an Element.ClassNames
object
representing the CSS class names of element
.
add(
className
)
Includes className
in the list of class names
associated with the element.
remove(
className
)
Removes className
from the list of CSS class names
associated with the element.
set(
className
)
Associates the element with className
, removing any
other class names from the element.
In addition to the methods listed here, Element.ClassNames
is also extended by the Enumerable methods.
The Form
object provides some utility functions for
working with data entry forms and their input fields. Note that_Form.*
_is mixed into $()
and $$()
calls.
serialize(
form
)
Returns a URL-formatted list of field names and their values, for example:
'field1=value1&field2=value2&field3=value3'
.
findFirstElement(
form
)
Returns the first enabled field element in form
.
getElements(
form
)
Returns an array containing all the input fields in
form
.
getInputs(
form
[,
typeName
[,
name
]])
Returns an array containing all the <input>
elements in form
. Optionally,
the list can be filtered by the typeName
or
name
attributes of the elements.
disable(
form
)
Disables all the input fields in the form.
enable(
form
)
Enables all the input fields in the form.
focusFirstElement(
form
)
Activates the first visible, enabled input field in the form.
reset(
form
)
Resets the form. The same as calling the reset()
method of the form object.
The Form.Element
object (aliased as Field
) provides some utility functions for working with form
inputs. Note that Form.Element.*
_is mixed into $()
and $$()
calls.
$F(
element
)
returns the value of any field input control, like a text box
or a drop-down list. element
can be either the id string or the
element object itself:
// <input type="text" id="userName" value="Joe Doe"> // <select id="state"> // <option value="NY">New York</option> // <option value="CA" selected="selected">California</option> // </select> $F('userName'), // => "Joe Doe" $F('state'), // => "CA"
serialize(
element
)
Returns element
’s name=value pair; for example:
'elementName=elementValue'
.
getValue(
element
)
Returns the value of element
.
clear(
field1
[,
field2
[...]])
Clears the value of each passed field
.
present(
field1
[,
field2
[...]])
Returns true
only if all
field
s contain non-empty
values.
focus(
field
)
Moves the input focus to field
.
select(
field
)
Selects the value in field
that supports text
selection.
activate(
field
)
Move the focus and selects the value in field
that
supports text selection
The Abstract.TimedObserver
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 such as the input value of an element, one of the style properties, the number of rows in a table, or whatever else you may be interested in tracking changes to.
Derived classes have to implement this method to determine the current value being monitored in the element.
initialize(
element
,
frequency
,
callback
)
Creates an object that will monitor element
every
frequency
in seconds and call
callback
when the element changes.
registerCallback()
This method is typically not called externally. It is called by the object itself to start monitoring the element.
onTimerEvent()
This method is typically not called externally. It is called by the object itself periodically to check the element.
element
The element object that is being monitored.
frequency
The interval in seconds between checks.
callback
The function (conforming to Function
(
Object
,
String
)
) to be called
whenever the element changes. It will receive the element object and the new
value.
lastValue
A string with the last value verified in the element.
Form.Element.Observer
is an implementation of
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.
initialize(
element
,
frequency
,
callback
)
Inherited from Abstract.TimedObserver
. Creates
an object that will monitor element
’s value
property every frequency
seconds and call callback
with its changes.
getValue()
Returns element
’s value.
Form.Observer
is an implementation of 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 elements that do not expose an event that reports the value changes. If the form
exposes an event, use the Form.EventObserver
class
instead.
initialize(
form
,
frequency
,
callback
)
Inherited from Abstract.TimedObserver
. Creates
an object that will monitor form
for changes every
frequency
seconds and call
callback
when any data entry element in the form
changes.
getValue()
Returns the serialization of all form
’s data.
The Abstract.EventObserver
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
list boxes/dropdowns.
Derived classes have to implement this method to determine the current value being monitored in the element.
initialize(
element
,
callback
)
Creates an object that will monitor element
and call
callback
when the event happens.
registerCallback()
This method is typically not called externally. It is called by the object to bind itself to the element’s event.
registerFormCallbacks()
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()
This method is typically not called externally. It will be bound to the element’s event.
element
The element object that is being monitored.
callback
The function (conforming to Function
(
Object
,
String
)
) to be called
whenever the element changes. It will receive the element object and the new
value.
lastValue
A string with the last value verified in the element.
Form.Element.EventObserver
is an implementation of
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.
initialize(
element
,
callback
)
Inherited from Abstract.EventObserver
. Creates
an object that monitors element
’s value
property and calls callback
when the
event happens.
getValue()
Returns the element’s value.
Form.EventObserver
is an implementation of 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.Observer
class instead.
initialize(
form
,
callback
)
Inherited from Abstract.EventObserver
. Creates
an object that will monitor form
for changes and call
callback
when any data entry element in the form
changes.
getValue()
Returns the serialization of all form
’s data.
This class is used as the base class for the other classes that will provide dynamic content insertion. This class is used like an abstract class.
initialize(
element
,
content
)
Creates an object that will help with dynamic content insertion.
contentFromAnonymousTable()
adjacency
A string that specifies where the content will be placed relative to the given
element. The possible values are: 'beforeBegin'
,
'afterBegin'
, 'beforeEnd'
, and 'afterEnd'
.
element
The element object that the insertion will be made relative to.
content
The content to be inserted.
Inherits from Abstract.Insertion
. Inserts
content
before element
.
The following code
<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span> <script> new Insertion.Before('person', 'Chief '), </script>
changes the HTML to
<br>Hello, Chief <span id="person" style="color:red;">Wiggum. How's it going?</span>
Inherits from Abstract.Insertion
. Inserts
content
as the first child under
element
; i.e., after the opening tag of
element
.
The following code
<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span> <script> new Insertion.Top('person', 'Mr. '), </script>
will change the HTML to
<br>Hello, <span id="person" style="color:red;">Mr. Wiggum. How's it going?</span>
Inherits from Abstract.Insertion
. Inserts
content
as the last child under
element
; i.e., before element
’s
closing tag.
The following code
<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span> <script> new Insertion.Bottom('person', " What's up?"); </script>
will change the HTML to
<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going? What's up?< /span>
Inherits from Abstract.Insertion
. Inserts
content
after element
’s closing
tag.
The following code
<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span> <script> new Insertion.After('person', ' Are you there?'), </script>
will change the HTML to
<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span> Are you there?
The Position
object provides a host of functions that
help when working with element positioning.
prepare()
Adjusts the deltaX
and deltaY
properties to accommodate changes in the scroll position. Remember
to call this method before any calls to withinIncludingScrolloffset
after the page scrolls.
realOffset(
element
)
Returns an Array
with the correct scroll
offsets of element
, including any scroll offsets that
affect element
. The resulting array is similar to [total_scroll_left, total_scroll_top]
.
cumulativeOffset(element)
Returns an Array
with the correct positioning
offsets of element
, including any offsets that are imposed
by positioned parent elements. The resulting array is similar to [total_offset_left, total_offset_top]
.
within(
element
,
x
,
y
)
Tests if the given point coordinates x
and
y
are inside the bounding rectangle of
element
.
withinIncludingScrolloffsets(
element
,
x
,
y
)
overlap(
mode
,
element
)
mode
should be 'vertical'
or 'horizontal'
. within()
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).
clone(
source
,
target
)
Resizes and repositions the element target
identically
to source
.
The $A(
object
)
method converts object
into an
array. Combined with the extensions for the Array
class,
this makes it easier to convert or copy any enumerable list into an array. One suggested use
is to convert DOM NodeLists
into regular arrays, which
can be traversed more efficiently.
clear()
Empties the array and returns itself.
compact()
Returns the array without the elements that are null
or undefined
. This method does
not change the array itself.
first()
Returns the first element of the array.
flatten()
Returns a flat, one-dimensional version of the array. This flattening happens by finding each of the array’s elements that are also arrays and including their elements in the returned array, recursively.
indexOf(
value
)
Returns t
he zero-based position of the given
value
if it is found in the array. Returns -1
if value
is not
found..
inspect()
Overridden to return a nicely formatted string representation of the array with its elements.
reverse([
applyToSelf
])
Returns the array in reverse sequence. If applyToSelf
is omitted or true
, the array itself will also be
reversed; otherwise, it remains unchanged.
shift()
Returns the first element and removes it from the array, reducing the array’s length by 1.
without(
value1
[, value2 [, ...]])
Returns the array, excluding the elements that are included in the list of arguments.
In addition to the extensions listed here, Array
is
also extended by the Enumerable methods.
// <select id="state"> // <option value="NY">New York</option> // <option value="CA">California</option> // </select> var nodeList = $('state').getElementsByTagName('option'), $A(nodeList).collect(function(node){ return node.nodeName + ': ' + node.innerHTML; }); // => ['OPTION: New York', 'OPTION: California']
The Hash
object implements a hash structure—a
collection of key/value pairs. Each member in a Hash
object is an array with two elements: the key and the value, which can be accessed via two
properties, key
and value
. The $H(
object
)
method
converts object
into a Hash
object.
keys()
Returns an Array
with the keys of all
items.
values()
Returns an Array
with the values of all
items.
merge(
otherHash
)
Combines the hash with otherHash
and returns the new
resulting hash.
toQueryString()
Returns all the items of the hash in a string formatted like a query string; e.g.,
'key1=value1&key2=value2&key3=value3'
.
inspect()
Overridden to return a nicely formatted string representation of the hash with its key/value pairs.
In addition to the extensions listed here, Hash
is
also extended by the Enumerable methods.
An instance of the ObjectRange
class represents a
range of values, with upper and lower bounds. The $R(
start
,
end
,
exclusive
)
method creates a
new ObjectRange
instance.
initialize(
start
,
end
,
exclusive
)
Creates a 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. If exclusive is true, includes
start
and end
in the
range.
include(
searchedValue
)
Checks if searchedValue
is part of the range. Returns
true
or false
.
start
An object of any type representing the lower bound of the range.
end
An object of any type representing the upper bound of the range.
exclusive
A Boolean determining if the boundaries themselves are part of the range.
In addition to the extensions listed here, ObjectRange
is also extended by the Enumerable methods.
The Enumerable
object contains methods for iterating
over items in a list-like structure. The methods are added to other classes, such as
Array
, Hash
, and
ObjectRange
. Most of the Enumerable
methods accept an iterator argument—a function
that will be applied to each member of the collection. In all methods, the argument
interator
is a function object conforming to
Function
(
value
,
index
)
.
each(
iterator
)
Calls iterator
passing each element in the list in the
first argument and the index of the element in the second argument.
all([
iterator
])
This function is a way to test the entire collection of values using a given
function. all
will return false
if iterator
returns false
or null
for any
of the elements. It will return true
otherwise. If
iterator
is not given, then the test will be if the
element itself is different than false
or null
. You can simply read it as “check if all elements are
not-false.”
any([
iterator
])
This function is a way to test the entire collection of values using a given
function. any
will return true
if iterator
does not return false
or null
for any
of the elements. It will return false
otherwise. If
iterator
is not given, then the test will be if the
element itself is different than false
or null
. You can simply read it as “check if any element is
not-false.”
collect(
iterator
)
Calls iterator
for each element in the collection and
returns each result in an Array
, one result element
for each element in the collection, in the same sequence.
detect(
iterator
)
Calls iterator
for each element in the collection and
returns the first element that caused iterator
to return
true (or, more precisely, not-false). Returns null if no element returns true.
entries()
Same as toArray()
.
find(
iterator
)
Same as detect()
.
findAll(
iterator
)
Calls iterator
for each element in the collection and
returns an Array
with all the elements that caused
iterator
to return a value that resolves to true
. This function is the opposite of reject()
.
grep(pattern [,
iterator
])
Tests the string value of each element in the collection against the pattern
(a RegExp
object). The function will return an Array
containing all the elements that matched pattern
.
If iterator
is given, then the Array
will contain the result of calling
iterator
with each element that was a match.
include(
obj
)
Tries to find obj
(any object) in the collection.
Returns true
if the object is found, false
otherwise.
inject(
initialValue
,
iterator
)
Unlike the other Enumerable
methods, inject
’s iterator
argument
should conform to Function(accumulator, value, index). Combines all the elements of
the collection using iterator
. The iterator is called
passing the result of the previous iteration in the
accumulator
argument, except the first iteration, which
gets initialValue
(which can be any object). The last
result is the final return value.
invoke(methodName [,
arg1
[,
arg2
[...]]])
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
)
Same as collect()
.
max([
iterator
])
Returns the element with the greatest value in the collection or the greatest
result of calling iterator
on each element in the
collection, if iterator
is given.
member(
obj
)
Same as include()
.
min([
iterator
])
Returns the element with the lowest value in the collection or the lowest result
of calling iterator
on each element in the collection, if
iterator
is given.
partition([
iterator
])
Returns an Array
containing two other arrays.
The first array will contain all the elements that caused
iterator
to return true
and the second array will contain the remaining elements. If
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)
Retrieves the value of the property specified by
propertyName
(which can also be the index of the element)
in each element of the collection and returns the results in an Array
object.
reject(
iterator
)
Calls iterator
for each element in the collection and
returns an Array
with all the elements that caused
iterator
to return a value that resolves to false
. This function is the opposite of findAll()
.
select(
iterator
)
Same as findAll()
.
sortBy(
iterator
)
Returns an Array
with all the elements sorted
according to the result of the iterator
call.
toArray()
Returns an Array
with all the elements of the
collection.
zip(collection1[,
collection2
[, ...
collectionN
[,
transform
]]])
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 of the elements with the same
index from each of the merged collections. If transform
is
given (a function object conforming to Function
(
value
,
index
)
), 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] ]"
.
Consider a simple example of Enumerable
’s each()
method:
['Bart', 'Lisa', 'Maggie'].each(function(name) { alert(name); } );
Because the Enumerable
methods are mixed into the
Array
class, each()
can be used as an instance method on a normal array. The method takes
one argument, an iterator function, which is called once for each element in the
array.
Consider a more complex example. Here we’ll find an element according to some
criteria, using Enumerable
’s find()
method.
// <select id="employees"> // <option value="5">Buchanan, Steven</option> // <option value="8">Callahan, Laura</option> // <option value="1">Davolio, Nancy</option> // </select> function findEmployeeById(id){ return $$('#employees option'). find( function(employee){ return (employee.value == id); }).innerHTML; } findEmployeeById(8); // => "Callahan, Laura"
stripTags()
Returns the string with any HTML or XML tags removed.
stripScripts()
Returns the string with any <script />
blocks removed.
escapeHTML()
Returns the string with any HTML markup characters properly escaped.
unescapeHTML()
The reverse of escapeHTML()
.
extractScripts()
Returns an Array
object containing all the
<script />
blocks found in the
string.
evalScripts()
Evaluates each <script />
block found in
the string.
toQueryParams()
Splits a querystring into an associative Array
indexed by parameter name (more like a hash).
parseQuery()
Same as toQueryParams()
.
toArray()
Splits the string into an Array
of its
characters.
camelize()
Converts a hyphen-delimited-string into a camelCaseString. This function is useful when writing code that deals with style properties, for example.
toColorPart()
Returns the hexadecimal representation of the number. Useful when converting the RGB components of a color into its HTML representation.
succ()
Returns the next number. This function is used in scenarios that involve iteration.
times(
iterator
)
Calls iterator
(a function object conforming to
Function
(
index
)
)
repeatedly passing the current index.
element(
event
)
Returns element that originated event
.
isLeftClick(
event
)
Returns true
if the left mouse button was
clicked.
pointerX(
event
)
Returns the x coordinate of the mouse pointer on the page.
pointerY(
event
)
Returns the y coordinate of the mouse pointer on the page.
stop(
event
)
Use this function to abort the default behavior of
event
and to suspend its propagation.
findElement(
event
,
tagName
)
Traverses the DOM tree upwards, searching for the first element named
tagName
, starting from the element that originated
event
.
observe(
element
,
name
,
observer
,
useCapture
)
Adds an event handler function observer
to
element
for the event named
name
(e.g., ‘click', ‘load', etc). If
useCapture
is true
, it
handles the event in the capture phase and if false
in the bubbling phase.
stopObserving(element, name, observer,
useCapture)
Removes an event handler named name
from
element
. observer
is the function that is handling the event. If useCapture
is true, it handles the event in the capture
phase and if false in the bubbling phase.
KEY_BACKSPACE
Code for the Backspace key (8
).
KEY_TAB
Code for the Tab key (9
).
KEY_RETURN
Code for the Return key (13
).
KEY_ESC
Code for the Esc key (27
).
KEY_LEFT
Code for the Left arrow key (37
).
KEY_UP
Code for the Up arrow key (38
).
KEY_RIGHT
Code for the Right arrow key (39
).
KEY_DOWN
Code for the Down arrow key (30
).
KEY_DELETE
Code for the Delete key (46
).
observers
Array of cached observers.
bind(
object
)
Returns an instance of the function pre-bound to the function(=method)
owner object
. The returned
function will have the same arguments as the original one.
bindAsEventListener(
object
)
Returns an instance of the function pre-bound to the function(=method)
owner object
. The returned
function will have the current event
object as its
argument.
// <input type="checkbox" id="checkbox" value="1"> var CheckboxWatcher = Class.create(); CheckboxWatcher.prototype = { initialize: function(chkBox, message) { this.chkBox = $(chkBox); this.message = message; this.chkBox.onclick = this.showMessage.bindAsEventListener(this); }, showMessage: function(evt) { alert(this.message + ' (' + evt.type + ')'), } }; new CheckboxWatcher('checkbox', 'Changed'),
extend(
destination
,
source
)
Copies all properties and methods from source
to
destination
, providing a way to implement
inheritance.
inspect(
targetObj
)
Returns a human-readable string representation of
targetObj
. If targetObj
doesn’t define an inspect()
method, defaults to the
return value of toString()
.
The Class
object is used when declaring the other
classes in the library. Using this object when declaring a class causes the new class to
support an initialize()
method, which serves as the
constructor.
create()
Defines a constructor for a new class.
The PeriodicalExecuter
class provides the logic for
calling a given function repeatedly, at a given interval.
initialize(
callback
,
interval
)
Creates a PeriodicalExecuter
instance that will
call callback
every interval
seconds.
callback
The function to be called. No parameters will be passed to it.
frequency
This is actually the interval in seconds.
currentlyExecuting
A boolean indicating if the function call is in progress.
Makes it easy to try different function calls until one of them works. Takes any 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.
The Prototype
object does not have any important
role, other than declaring the version of the library being used.
Version
A string containing the version of the library.
emptyFunction()
An empty function object.
K()
A function object that just echoes back the given parameter.
ScriptFragment
A string describing a regular expression to identify scripts.