PrototypeReference

Examples and explanations

Created by: xing, Last modification: 23 Dec 2005 (17:53 UTC)

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


Method Kind Arguments Description
extend(destination, source) static destination: any object, source: any object Provides a way to implement inheritance by copying all properties and methods from source to destination.
extend(object) instance any object Provides a way to implement inheritance by copying all properties and methods from the given object.


Extensions for the Number class


Method Kind Arguments Description
toColorPart() instance (none) Returns the hexadecimal representation of the number. Useful when converting the RGB components of a color into its HTML representation.


Extensions for the Function class


Method Kind Arguments Description
bind(object) instance object: the object that owns the method 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) instance object: the object that owns the method 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.


Let's see one of these extensions in action.


<input type=checkbox id=myChk value=1 /> Test?
<script>
    //declaring the class
    var CheckboxWatcher = Class.create();

    //defining the rest of the class implmentation
    CheckboxWatcher.prototype = {
        initialize: function(chkBox, message) {
            this.chkBox = $(chkBox);
            this.message = message;
            //assigning our method to the event
            this.chkBox.onclick = this.showMessage.bindAsEventListener(this);
        },

        showMessage: function(evt) {
            alert(this.message + ' (' + evt.type + ')');
        }
    };

    var watcher = new CheckboxWatcher('myChk', 'Changed');
</script>


Extensions for the String class


Method Kind Arguments Description
stripTags() instance (none) Returns the string with any HTML or XML tags removed
escapeHTML() instance (none) Returns the string with any HTML markup characters properly escaped
unescapeHTML() instance (none) The reverse of escapeHTML()


Extensions for the document DOM object


Method Kind Arguments Description
getElementsByClassName(className) instance className: name of a CSS class associated with the elements Returns all the elements that are associated with the given class name.


Extensions for the Event object


Property Type Description
KEY_BACKSPACE Number 8: Constant. Code for the Backspace key.
KEY_TAB Number 9: Constant. Code for the Tab key.
KEY_RETURN Number 13: Constant. Code for the Return key.
KEY_ESC Number 27: Constant. Code for the Esc key.
KEY_LEFT Number 37: Constant. Code for the Left arrow key.
KEY_UP Number 38: Constant. Code for the Up arrow key.
KEY_RIGHT Number 39: Constant. Code for the Right arrow key.
KEY_DOWN Number 40: Constant. Code for the Down arrow key.
KEY_DELETE Number 46: Constant. Code for the Delete key.
observers: Array List of cached observers. Part of the internal implementation details of the object.


Method Kind Arguments Description
element(event) static event: an Event object Returns element that originated the event.
isLeftClick(event) static event: an Event object Returns true if the left mouse button was clicked.
pointerX(event) static event: an Event object Returns the x coordinate of the mouse pointer on the page.
pointerY(event) static event: an Event object Returns the y coordinate of the mouse pointer on the page.
stop(event) static event: an Event object Use this function to abort the default behavior of an event and to suspend its propagation.
findElement(event, tagName) static event: 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) static element: object or id, name: event name (like 'click', 'load', etc), observer: function to handle the event, useCapture: if true, handles the event in the capture phase and if false in the bubbling phase. Adds an event handler function to an event.
stopObserving(element, name, observer, useCapture) static element: 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.


<script>
    Event.observe(window, 'load', showMessage, false);

    function showMessage() {
      alert('Page loaded.');
    }
</script>


New objects and classes defined by prototype.js


Another way the library helps you is by providing many objects 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.

Method Kind Arguments Description
ctor(callback, interval) constructor callback: a parameterless function, interval: number of seconds Creates one instance of this object that will call the function repeatedly.


Property Type Description
callback Function() The function to be called. No parameters will be passed to it.
frequency Number This is actually the interval in seconds
currentlyExecuting Boolean Indicates if the function call is in progress


The Prototype object


The Prototype object does not have any important role, other than declaring the version of the library being used.

Property Type Description
Version String The version of the library
emptyFunction Function() An empty function object


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 an initialize() method, which serves as the constructor.

See the sample below.


<script>
    //declaring the class
    var MySampleClass = Class.create();

    //defining the rest of the class implmentation
    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
</script>


Method Kind Arguments Description
create(*) instance (any) Defines a constructor for a new class


The Ajax object


This object serves as the root for many other classes that provide AJAX functionality.

Method Kind Arguments Description
getTransport() instance (none) Returns a new XMLHttpRequest object


The Ajax.Base class


This class is used as the base class for the other classes defined in the Ajax object.

Method Kind Arguments Description
setOptions(options) instance options: AJAX options Sets 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

Property Type Kind Description
Events Array static List of possible events/statuses reported during an AJAX operation. The list contains: 'Uninitialized', 'Loading', 'Loaded', 'Interactive', and 'Complete.'
transport XMLHttpRequest instance The XMLHttpRequest object that carries the AJAX operation


Method Kind Arguments Description
ctor(url, options) constructor url: the url to be fetched, options: AJAX options Creates one instance of this object that will call the given url using the given options. Important: It is worth noting that the chosen url is subject to the borwser'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).
request(url) instance url: url for the AJAX call This method is typically not called externally. It is already called during the constructor call.
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.
onStateChange() instance (none) This method is typically not called externally. It is called by the object itself when the AJAX call status changes.
respondToReadyState(readyState) instance readyState: 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.


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.

Property Type Default Description
method String 'post' Method of the HTTP request
parameters String The url-formatted list of values passed to the request
asynchronous Boolean true Indicates if the AJAX call will be made asynchronously
postBody String undefined Content passed to in the request's body in case of a HTTP POST
requestHeaders Array undefined List 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''>'my-header1', 'this is the value', 'my-other-header', 'another value'
onXXXXXXXX Function(XMLHttpRequest) undefined Custom function to be called when the respective event/status is reached during the AJAX call. Example var myOpts = {onComplete: showResponse, onLoaded: registerLoaded};. The function used will receive one argument, containing the XMLHttpRequest object that is carrying the AJAX operation.
onSuccess Function(XMLHttpRequest) undefined Custom 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.
onFailure Function(XMLHttpRequest) undefined Custom 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.
insertion Function(Object, String) null Function to be called to inject the returned text into an element. The function will be called with two arguments, the element object to be updated and the response text Applies only to Ajax.Updater objects.
evalScripts Boolean undefined, false Determines if script blocks will be evaluated when the response arrives. Applies only to Ajax.Updater objects.
decay Number undefined, 1 Determines 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.


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 <script> blocks that will be evaluated upon arrival. Use the evalScripts option to work with scripts.

Property Type Kind Description
ScriptFragment String static A regular expression to identify scripts
containers Object instance This object contains two properties: containers.success will be used when the AJAX call succeeds, and containers.failure will be used otherwise.


Method Kind Arguments Description
ctor(container, url, options) constructor container:this can be the id of an element, the element object itself, or an object with two properties - object.success element (or id) that will be used when the AJAX call succeeds, and object.failure element (or id) that will be used otherwise. url: the url to be fetched, options: AJAX options Creates one instance of this object that will call the given url using the given options.
updateContent() instance (none) This method is typically not called externally. It is called by the object itself 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.


The Ajax.PeriodicalUpdater class


Inherits from Ajax.Base

This 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. Check the Ajax.Updater reference for more information.

Property Type Kind Description
container Object instance This value will be passed straight to the Ajax.Updater's constructor.
url String instance This value will be passed straight to the Ajax.Updater's constructor.
frequency Number instance Interval (not frequency) between refreshes, in seconds. Defaults to 2 seconds. This number will be multiplied by the current decay when invoking theAjax.Updater object
decay Number instance Keeps the current decay level applied when re-executing the task
updater Ajax.Updater instance The most recently used Ajax.Updater object
timer Object instance The JavaScript timer being used to notify the object when it is time for the next refresh.


Method Kind Arguments Description
ctor(container, url, options) constructor container:this can be the id of an element, the element object itself, or an object with two properties - object.success element (or id) that will be used when the AJAX call succeeds, and object.failure element (or id) that will be used otherwise. url: the url to be fetched, options: AJAX options Creates one instance of this object that will call the given url using the given options.
start() instance (none) This method is typically not called externally. It is called by the object itself to start performing its periodical tasks.
stop() instance (none) This method is typically not called externally. It is called by the object itself to stop performing its periodical tasks.
updateComplete() instance (none) This method is typically not called externally. It is called by the currently used Ajax.Updater after if completes the request. It is used to schedule the next refresh.
onTimerEvent() instance (none) This method is typically not called externally. It is called internally when it is time for the next update.


The Element object


This object provides some utility functions for manipulating elements in the DOM.

Method Kind Arguments Description
toggle(elem1 [, elem2 [, elem3 ...]]) instance elemN: element object or id Toggles the visibility of each passed element.
hide(elem1 [, elem2 [, elem3 ...]]) instance elemN: element object or id Hides each element by setting its style.display to 'none'.
show(elem1 [, elem2 [, elem3 ...]]) instance elemN: element object or id Shows each element by resetting its style.display to ''.
remove(element) instance element: element object or id Removes the element from the document.
getHeight(element) instance element: element object or id Returns the offsetHeight of the element
addClassName(element, className) instance element: element object or id, className: name of a CSS class Adds the given class name to the element's class names.
hasClassName(element, className) instance element: element object or id, className: name of a CSS class Returns true if the element has the given class name as one of its class names.
removeClassName(element, className) instance element: element object or id, className: name of a CSS class Removes the given class name from the element's class names.
cleanWhitespace(element) instance element: element object or id Removes any white space text node children of the element


The Abstract object


This object serves as the root for other classes in the library. It does not have any properties or methods. The classes defined in this object are also treated as traditional abstract classes.

The Abstract.Insertion class


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.

Method Kind Arguments Description
ctor(element, content) constructor element: element object or id, content: HTML to be inserted Creates an object that will help with dynamic content insertion.


Property Type Kind Description
adjacency String static, parameter Parameter that specifies where the content will be placed relative to the given element. The possible values are: 'beforeBegin', 'afterBegin', 'beforeEnd', and 'afterEnd'.
element Object instance The element object that the insertion will be made relative to.
content String instance The HTML that will be inserted.

The Insertion object


This object serves as the root for other classes in the library. It does not have any properties or methods. The classes defined in this object are also treated as traditional abstract classes.

The Insertion.Before class


Inherits from Abstract.Insertion

Inserts HTML before an element.

Method Kind Arguments Description
ctor(element, content) constructor element: element object or id, content: HTML to be inserted Inherited from Abstract.Insertion. Creates an object that will help with dynamic content insertion.


The following code


<br>Hello, <span id="person" style="color:red;">Wiggum. How is it going?</span>
<script> new Insertion.Before('person', 'Chief '); </script>


Will change the HTML to


<br>Hello, Chief <span id="person" style="color:red;">Wiggum. How is it going?</span>


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.

Method Kind Arguments Description
ctor(element, content) constructor element: element object or id, content: HTML to be inserted Inherited from Abstract.Insertion. Creates an object that will help with dynamic content insertion.


The following code


<br>Hello, <span id="person" style="color:red;">Wiggum. How is it going?</span>
<script> new Insertion.Before('person', 'Mr. '); </script>


Will change the HTML to


<br>Hello, <span id="person" style="color:red;">Mr. Wiggum. How is it going?</span>


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.

Method Kind Arguments Description
ctor(element, content) constructor element: element object or id, content: HTML to be inserted Inherited from Abstract.Insertion. Creates an object that will help with dynamic content insertion.


The following code


<br>Hello, <span id="person" style="color:red;">Wiggum. How is it going?</span>
<script> new Insertion.Before('person', ' What's up?'); </script>


Will change the HTML to


<br>Hello, <span id="person" style="color:red;">Wiggum. How is it going? What's up?</span>


The Insertion.After class


Inherits from Abstract.Insertion

Inserts HTML right after the element's closing tag.

Method Kind Arguments Description
ctor(element, content) constructor element: element object or id, content: HTML to be inserted Inherited from Abstract.Insertion. Creates an object that will help with dynamic content insertion.


The following code


<br>Hello, <span id="person" style="color:red;">Wiggum. How is it going?</span>
<script> new Insertion.Before('person', ' Are you there?'); </script>


Will change the HTML to


<br>Hello, <span id="person" style="color:red;">Wiggum. How is it going?</span> Are you there?


The Field object


This object provides some utility functions for working with input fields in forms.

Method Kind Arguments Description
clear(field1 [, field2 [, field3 ...]]) instance fieldN: field element object or id Clears the value of each passed form field element.
present(field1 [, field2 [, field3 ...]]) instance fieldN: field element object or id Returns true only if all forms fields contain non-empty values.
focus(field) instance field: field element object or id Moves the input focus to the given form field.
select(field) instance field: field element object or id Selects the value in fields that support text selection
activate(field) instance field: field element object or id Move the focus and selects the value in fields that support text selection


The Form object


This object provides some utility functions for working with data entry forms and their input fields.

Method Kind Arguments Description
serialize(form) instance form: form element object or id Returns a url-formatted list of field names and their values, like 'field1=value1&field2=value2&field3=value3'
getElements(form) instance form: form element object or id Returns an Array containing all the input fields in the form.
getInputs(form [, typeName , name]) instance form: 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 <input> elements in the form. Optionally, the list can be filtered by the type or name attributes of the elements.
disable(form) instance form: form element object or id Disables all the input fields in the form.
enable(form) instance form: form element object or id Enables all the input fields in the form.
focusFirstElement(form) instance form: form element object or id Activates the first visible, enabled input field in the form.
reset(form) instance form: form element object or id Resets 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, visible or not.

Method Kind Arguments Description
serialize(element) instance element: element object or id Returns the element's name=value pair, like 'elementName=elementValue'
getValue(element) instance element: element object or id Returns the value of the element.


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.

Method Kind Arguments Description
inputSelector(element) instance element: 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>'elementName', 'elementValue'
textarea(element) instance element: 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>'elementName', 'elementValue'
select(element) instance element: object or id of a <select> element Returns an Array with the element's name and all selected options' values or texts, like elementName', 'selOpt1 selOpt4 selOpt9>'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.

||Method | Kind | Arguments | Description
ctor(element, frequency, callback) | constructor | element: element object or id, frequency: interval in seconds, callback: function to be called when the element changes | Creates an object that will monitor the element.

Related Items

Documentation » Technical Documentation

Documentation geared towards developers and people who want to learn about the core processes of bitweaver

  •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •    •