Anotações de um desenvolvedor sobre a prototype.js

abrange a versão 1.3.1

por
Última atualização : 2 de outubro de 2005
Outros idiomas

O que é isso?

Caso você ainda não tenha tido a oportunidade de utilizá-la, prototype.js é uma ótima biblioteca javascript escrita por Sam Stephenson. Esta coleção de funções é impressionantemente bem escrita e bem pensada, utiliza técnicas de acordo com os padrões atuais e alivia seu trabalho na hora de produzir as páginas altamente interativas que caracterizam a chamada Web 2.0.

Se você andou tentando utilizar essa biblioteca recentemente, você provavelmente nottou que a documentação não pode ser considerada um de seus pontos fortes. Tal como muitos outros programadores fizeram, eu também só sonsegui entender como utilizar a prototype.js ao inspecionar seu código-fonte. Eu imaginei que poderia ser útil se eu fizesse algumas anotações enquanto eu aprendia e então compartilhasse com todo mundo.

Também estou incluindo aqui uma referência não-oficial para os objetos, classes, funções e extensões implementadas nessa biblioteca.

As funções utilitárias

A biblioteca vêm com diversos objetos pré-definidos e funções utilitárias. O objetivo claro dessas funções é evitar uma imensidão de digitação repetitiva e propensa a erros, que eu costumo comparar a musculação.

Utilizando a função $()

A função $() é um conveniente atalho para as inúmeras ocorrências da chamada à função document.getElementById() do DOM. Tal como a função do DOM, esta retorna o elemento que é identificado pelo valor id passado como argumento.

No entanto, diferentemente da função do DOM, essa vai mais além. Você pode passar mais de um argumento e a função $() retornará um objeto Array com todos os elementos requisitados. O exemplo a seguir ilustra esse fato.

<HTML>
<HEAD>
<TITLE> Test Page </TITLE>
<script src="prototype-1.3.1.js"></script>

<script>
	function test1()
	{
		var d = $('myDiv');
		alert(d.innerHTML);
	}

	function test2()
	{
		var divs = $('myDiv','myOtherDiv');
		for(i=0; i<divs.length; i++)
		{
			alert(divs[i].innerHTML);
		}
	}
</script>
</HEAD>

<BODY>
	<div id="myDiv">
		<p>This is a paragraph</p>
	</div>
	<div id="myOtherDiv">
		<p>This is another paragraph</p>
	</div>

	<input type="button" value=Test1 onclick="test1();"><br> 
	<input type="button" value=Test2 onclick="test2();"><br> 

</BODY>
</HTML>

Outro ponto interessante dessa função é que você pode passar tanto o valor string do id de um elemento quanto o próprio objeto do elemento. Isso deixa a função mais flexível e bastante prática quando se deseja criar outras funções que tratam os argumentos da mesma forma.

Usando a função $F()

A função $F() é outro atalho bem-vindo. Ela retorna o valor de qualquer campo de um formulário (input control) tais como caixas de texto ou listas. A função pode receber como parâmetro tanto o id do elemento como o próprio objeto do elemento.

<script>
	function test3()
	{
		alert(  $F('userName')  );
	}
</script>

<input type="text" id="userName" value="Joe Doe"><br> 
<input type="button" value=Test3 onclick="test3();"><br> 
			

Utilizando a função Try.these()

A função Try.these() facilita as coisas na hora que se torna necessário experimentar diferentes chamadas a funções até que uma funcione. Esta função aceita uma lista de chamadas a outras funções como argumento. Então cada chamada é executada na ordem dada, até que uma dê certo e então o resultado dessa chamada é retornado.

No exemplo a seguir, a propriedade xmlNode.text funciona em alguns browsers, e xmlNode.textContent funciona em outros browsers. Ao utilizarmos a função Try.these() nós podemos sempre retornar a chamada que funciona corretamente (sem erros).

<script>
function getXmlNodeValue(xmlNode){
	return Try.these(
		function() {return xmlNode.text;},
		function() {return xmlNode.textContent;)
		);
}
</script>
			

O objeto Ajax

Tá bem, as funções utilitárias mencionadas acima são legais mas convenhamos, elas também não são a coisa mais avançada que já se viu, não é? Você provavelmente poderia ter escrito essas funções sozinho ou talvez até você já tenha algumas funções semelhantes em seus próprios scripts. Só que essas funções são apenas a ponta do iceberg.

Eu tenho certeza que seu interesse pela prototype.js advém principalmente de suas capacidades relacionadas a AJAX. Então vamos explicar como a biblioteca facilita as coisas pra você quando é necessário implementar operações de AJAX.

O objeto Ajax é pré-definido na biblioteca, criado para encapsular e simplificar o código traiçoeiro que é necessário quando se implementam funcionalidades AJAX. Este objeto contém uma série de classes que disponibilizam lógica AJAX. Vamos dar uma olhada em algumas desas classes.

Utilizando a classe Ajax.Request

Se você não estiver utilizando nenhuma biblioteca auxiliar, você provavelmente está escrevendo uma montanha de código para criar um objeto XMLHttpRequest, acompanhar seu progresso assincronamente, e então extrair a resposta e processá-la. Considere-se um sortudo se você não precisa suportar mais de um tipo de browser.

Para auxiliar com operações AJAX, a biblioteca define a classe Ajax.Request.

Digamos que você tenha uma aplicação que pode se comunicar com o servidor através da url http://yoursever/app/get_sales?empID=1234&year=1998, que retorna uma resposta em XML similar à seguinte.

<?xml version="1.0" encoding="utf-8" ?> 
<ajax-response>
	<response type="object" id="productDetails">
		<monthly-sales>
			<employee-sales>
				<employee-id>1234</employee-id> 
				<year-month>1998-01</year-month> 
				<sales>$8,115.36</sales> 
			</employee-sales>
			<employee-sales>
				<employee-id>1234</employee-id> 
				<year-month>1998-02</year-month> 
				<sales>$11,147.51</sales> 
			</employee-sales>
		</monthly-sales>
	</response>
</ajax-response>			
			

Contactar o servidor para buscar esse XML é bastante simples utilizando um objeto Ajax.Request. O exemplo abaixo mostra como isso pode ser feito.

<script>
	function searchSales()
	{
		var empID = $F('lstEmployees');
		var y = $F('lstYears');
		var url = 'http://yoursever/app/get_sales';
		var pars = 'empID=' + empID + '&year=' + y;
		
var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onComplete: showResponse} );
} function showResponse(originalRequest) { //put returned XML in the textarea $('result').value = originalRequest.responseText; } </script> <select id="lstEmployees" size="10" onchange="searchSales()"> <option value="5">Buchanan, Steven</option> <option value="8">Callahan, Laura</option> <option value="1">Davolio, Nancy</option> </select> <select id="lstYears" size="3" onchange="searchSales()"> <option selected="selected" value="1996">1996</option> <option value="1997">1997</option> <option value="1998">1998</option> </select> <br><textarea id=result cols=60 rows=10 ></textarea>

Dá para você perceber o segundo parâmetro passado ao contrutor do objeto Ajax.Request? O parâmetro {method: 'get', parameters: pars, onComplete: showResponse} representa um objeto anônimo em notação literal (muito similar à notação JSON). O que ele significa é que estamos passando um objeto que tem uma propriedade chamada method que contém a string 'get', uma outra propriedade chamada parameters que contém a querystring da requisição HTTP, e uma propriedade/método onComplete contendo a função showResponse.

Ainda há mais algumas propriedades que você pode definir nesse objeto, tais como asynchronous, que pode ser true ou false e determina se a chamada AJAX ao servidor será feita de maneira assíncrona ou não (o valor default é true.)

Este parâmetro define as opções para a chamada AJAX. Em nosso exemplo estamos chamando a url do primeiro argumento através de um comando HTTP GET, passando a querystring contida na variável pars, e o objeto Ajax.Request irá chamar a função showResponse quando terminar de buscar receber a resposta.

Como se sabe, o objeto XMLHttpRequest anuncia o progresso durante a chamada HTTP. Este progresso pode representar quatro diferentes estágios:Loading (carregando), Loaded (carregado), Interactive (interativo), or Complete (completo). Você pode fazer com que o objeto Ajax.Request chame uma função sua em cada um desses estágios, sendo o Complete o mais comum. Para especificar a função para o objeto, basta utilizar propriedades/métodos chamados onXXXXX nas opções da chamada, tal como a propriedade onComplete em nosso exemplo anterior. A função especificada será chamada pelo objeto com um único argumento, que será o próprio objeto XMLHttpRequest. Você poderá então utilizar esse objeto para extrair os dados retornados e possivelmente checar a propriedade status, que informará o resultado (código) da chamada HTTP.

Duas outra opções interessantes podem ser utilizadas para processar os resultados. Nós podemos especificar a opção onSuccess como uma função a ser chamada quando a chamada AJAX executa sem erros. Analogamente, a opção onFailure pode ser espcificada como uma função a ser chamada quando um erro ocorrer durante a chamada. Tal como as funções onXXXXX, essas duas funções também serão chamadas com um argumento que conterá o objeto XMLHttpRequest que serviu de veículo para a chamada AJAX.

Nosso exemplo não fez nenhum processamento interessante da resposta XML. Nós apenas ecoamos o XML no textarea. Uma utilizaçãomais típica da resposta iria provavelmente extrair a informação desejada de dentro do XML e atualizar alguns elementos da página, ou talvez mesmo utilizar uma transformação XSLT para criar HTML e inserir na página.

Para maiores detalhes, dê uma olhada na referência do Ajax.Request e na referência das opções.

Utilizando a classe Ajax.Updater

Supondo que você tenha uma URL no seu servidor que possa retornar os dados já formatados em HTML, então a biblioteca facilita ainda mais sua vida com a classe Ajax.Updater. Com ela basta você informar qual o elemento que deve ser preenchido com o HTML que será retornado pela chamada AJAX. Um exemplo demonstra isso melhor do que eu conseguiria descrever.

<script>
	function getHTML()
	{
		var url = 'http://yourserver/app/getSomeHTML';
		var pars = 'someParameter=ABC';
		
var myAjax = new Ajax.Updater('placeholder', url, {method: 'get', parameters: pars});
} </script> <input type=button value=GetHtml onclick="getHTML()"> <div id="placeholder"></div>

Como você pode ver, o código é muito semelhante ao exemplo anterior, excluindo-se a função onComplete e passando-se o id do elemento no construtor. Vamos alterar um pouco o código para ilustrar como é possível tratar erros produzidos no servidor em seu código no cliente.

Vamos incluir mais opções na chamada, especificando uma função para capturar situações de erro. Isso se faz com o auxílio da opção onFailure. Vamos também especificar que o elemento de id placeholder apenas será preenchido se a operação for conc;uída com sucesso. Para que isso seja possível, vamos mudar o primeiro parametro de um simples id de elemento para um objeto. O construtor de Ajax.Updater aceita também como primeiro parâmetro um objeto com duas propriedades, success (a ser usado quando tudo termina bem) e failure (a ser usado quando um erro ocorre na chamada). No nosso caso não precisaremos da propriedade failure pois estaremos usando uma função nossa para tratar o erro. A função reportError tratará o erro conforme especificado na opção onFailure.

<script>
	function getHTML()
	{
		var url = 'http://yourserver/app/getSomeHTML';
		var pars = 'someParameter=ABC';
		
var myAjax = new Ajax.Updater( {success: 'placeholder'}, url, {method: 'get', parameters: pars, onFailure: reportError});
} function reportError(request) { alert('Sorry. There was an error.'); } </script> <input type=button value=GetHtml onclick="getHTML()"> <div id="placeholder"></div>

Um outro caso interessante é se seu servidor retorna código em JavaScript ou invés de HTML. O objeto Ajax.Updater pode avaliar o código JavaScript. Para fazer o objeto tratar a resposta do servidor como JavaScript, basta que você use a opção evalScripts: true;.

Para mais detalhes sobre essa classe, veja e referência do Ajax.Updater e a referência das opções.


Referência da prototype.js

Extensões das classes JavaScript

Uma das formas que prototype.js adiciona funcionalidade é extendendo as classes JavaScript existentes.

Extensões da classe Object

MétodoTipoArgumentosDescrição
extend(destination, source)estáticodestination: qualquer objeto, source: qualquer objeto Provém uma forma de se conseguir herança ao se copiar todas as propriedades e métodos de source para destination.
extend(object)de objetoqualquer objeto Provém uma forma de se conseguir herança ao se copiar todas as propriedades e métodos do object dado para o objeto atual.

Extensões da classe Number

MétodoTipoArgumentosDescrição
toColorPart()de objeto(nenhum) Retorna a representação hexadecimal do número. Útil quando se quer converter valores RGB de uma cor para seu formato em HTML.

Extensões da classe Function

MétodoTipoArgumentosDescrição
bind(object)de objetoobject: o objeto ao qual o método pertence Retorna uma instância da função atrelada ao objeto que à contém. A nova função têm os mesmos argumentos que a original.
bindAsEventListener(object)de objetoobject: o objeto ao qual o método pertence Retorna uma instância da função atrelada ao objeto que à contém. A nova função terá o objeto event atual como argumento.

Vamos ver como se usam essas extensões.

<input type=checkbox id=myChk value=1> Test?
<script>
	//declarando a classe
	var CheckboxWatcher = Class.create();

	//definindo o resto da classe
	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>

			

Extensões da classe String

MétodoTipoArgumentosDescrição
stripTags()de objeto(nenhum) Returns the string with any HTML or XML tags removed
escapeHTML()de objeto(nenhum) Returns the string with any HTML markup characters properle escaped
unescapeHTML()de objeto(nenhum) The reverse of escapeHTML()

Extensões da classe document DOM object

MétodoTipoArgumentosDescrição
getElementsByClassName(className)de objeto className: name of a CSS class associated with the elements Returns all the elements that are associated with the given class name.

Extensões da classe Event object

PropriedadeTipoDescrição
KEY_BACKSPACENumber 8: Constant. Code for the Backspace key.
KEY_TABNumber 9: Constant. Code for the Tab key.
KEY_RETURNNumber 13: Constant. Code for the Return key.
KEY_ESCNumber 27: Constant. Code for the Esc key.
KEY_LEFTNumber 37: Constant. Code for the Left arrow key.
KEY_UPNumber 38: Constant. Code for the Up arrow key.
KEY_RIGHTNumber 39: Constant. Code for the Right arrow key.
KEY_DOWNNumber 40: Constant. Code for the Down arrow key.
KEY_DELETENumber 46: Constant. Code for the Delete key.
observers:Array List of cached observers. Part of the internal implementation details of the object.

MétodoTipoArgumentosDescrição
element(event)estático event: an Event object Returns element that originated the event.
isLeftClick(event)estático event: an Event object Returns true if the left mouse button was clicked.
pointerX(event)estático event: an Event object Returns the x coordinate of the mouse pointer on the page.
pointerY(event)estático event: an Event object Returns the y coordinate of the mouse pointer on the page.
stop(event)estático event: an Event object Use this function to abort the default behavior of an event and to suspend its propagation.
findElement(event, tagName)estático 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)estático 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)estático 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)estático   Private method, do not worry about it.
unloadCache()estático (nenhum) 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.

MétodoTipoArgumentosDescrição
[ctor](callback, interval)constructorcallback: a parameterless function, interval: number of seconds Creates one instance of this object that will call the function repeatedly.

PropriedadeTipoDescrição
callbackFunction()The function to be called. No parameters will be passed to it.
frequencyNumberThis is actually the interval in seconds
currentlyExecutingBooleanIndicates 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.

PropriedadeTipoDescrição
VersionStringThe version of the library
emptyFunctionFunction()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.

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

			

MétodoTipoArgumentosDescrição
create(*)de objeto(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.

MétodoTipoArgumentosDescrição
getTransport()de objeto(nenhum) Returns a new XMLHttpRequest object

The Ajax.Base

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

MétodoTipoArgumentosDescrição
setOptions(options)de objetooptions: AJAX options Sets the desired options for the AJAX operation
responseIsSuccess()de objeto(nenhum) Returns true if the AJAX operation succeeded, false otherwise
responseIsFailure()de objeto(nenhum) The opposite of responseIsSuccess().

The Ajax.Request

Inherits from Ajax.Base

Encapsulates AJAX operations

PropriedadeTipoTipoDescrição
EventsArrayestático List of possible events/statuses reported during an AJAX operation. The list contains: 'Uninitialized', 'Loading', 'Loaded', 'Interactive', and 'Complete.'
transportXMLHttpRequestde objeto The XMLHttpRequest object that carries the AJAX operation

MétodoTipoArgumentosDescrição
[ctor](url, options)constructorurl: 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)de objetourl: url for the AJAX call This method is typically not called externally. It is already called during the constructor call.
setRequestHeaders()de objeto(nenhum) 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()de objeto(nenhum) This method is typically not called externally. It is called by the object itself when the AJAX call status changes.
respondToReadyState(readyState)de objetoreadyState: 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.

PropriedadeTipoDefaultDescrição
methodString'post' Method of the HTTP request
parametersString'' The url-formatted list of values passed to the request
asynchronousBooleantrue Indicates if the AJAX call will be made asynchronously
postBodyStringundefined Content passed to in the request's body in case of a HTTP POST
requestHeadersArrayundefined 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']
onXXXXXXXXFunction(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.
onSuccessFunction(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.
onFailureFunction(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.
insertionFunction(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.
evalScriptsBooleanundefined, false Determines if script blocks will be evaluated when the response arrives. Applies only to Ajax.Updater objects.
decayNumberundefined, 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

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.

PropriedadeTipoTipoDescrição
ScriptFragmentStringestático A regular expression to identify scripts
containersObjectde objeto This object contains two properties: containers.success will be used when the AJAX call succeeds, and containers.failure will be used otherwise.

MétodoTipoArgumentosDescrição
[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()de objeto(nenhum) 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

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.

PropriedadeTipoTipoDescrição
containerObjectde objeto This value will be passed straight to the Ajax.Updater's constructor.
urlStringde objeto This value will be passed straight to the Ajax.Updater's constructor.
frequencyNumberde objeto 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
decayNumberde objeto Keeps the current decay level applied when re-executing the task
updaterAjax.Updaterde objeto The most recently used Ajax.Updater object
timerObjectde objeto The JavaScript timer being used to notify the object when it is time for the next refresh.

MétodoTipoArgumentosDescrição
[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()de objeto(nenhum) This method is typically not called externally. It is called by the object itself to start performing its periodical tasks.
stop()de objeto(nenhum) This method is typically not called externally. It is called by the object itself to stop performing its periodical tasks.
updateComplete()de objeto(nenhum) 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()de objeto(nenhum) 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.

MétodoTipoArgumentosDescrição
toggle(elem1 [, elem2 [, elem3 [...]]])de objetoelemN: element object or id Toggles the visibility of each passed element.
hide(elem1 [, elem2 [, elem3 [...]]])de objetoelemN: element object or id Hides each element bu setting its style.display to 'none'.
show(elem1 [, elem2 [, elem3 [...]]])de objetoelemN: element object or id Shows each element bu resetting its style.display to ''.
remove(element)de objetoelement: element object or id Removes the element from the document.
getHeight(element)de objetoelement: element object or id Returns the offsetHeight of the element
addClassName(element, className)de objetoelement: element object or id, className: name of a CSS class Adds the given class name to the element's class names.
hasClassName(element, className)de objetoelement: 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)de objetoelement: element object or id, className: name of a CSS class Removes the given class name from the element's class names.
cleanWhitespace(element)de objetoelement: 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

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.

MétodoTipoArgumentosDescrição
[ctor](element, content)constructor element: element object or id, content: HTML to be inserted Creates an object that will help with dynamic content insertion.

PropriedadeTipoTipoDescrição
adjacencyStringstatic, parameter Parameter that specifies where the content will be placed relative to the given element. The possible values are: 'beforeBegin', 'afterBegin', 'beforeEnd', and 'afterEnd'.
elementObjectde objeto The element object that the insertion will be made relative to.
contentStringde objeto 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

Inherits from Abstract.Insertion

Inserts HTML before an element.

MétodoTipoArgumentosDescrição
[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's 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's it going?</span>	
			

The Insertion.Top

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.

MétodoTipoArgumentosDescrição
[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'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>	
			

The Insertion.Bottom

Inherits from Abstract.Insertion

Inserts HTML as the last child under an element. The content will be right before the element's closing tag.

MétodoTipoArgumentosDescrição
[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'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>	
			

The Insertion.After

Inherits from Abstract.Insertion

Inserts HTML right after the element's closing tag.

MétodoTipoArgumentosDescrição
[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'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 Field object

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

MétodoTipoArgumentosDescrição
clear(field1 [, field2 [, field3 [...]]])de objetofieldN: field element object or id Clears the value of each passed form field element.
present(field1 [, field2 [, field3 [...]]])de objetofieldN: field element object or id Returns true only if all forms fields contain non-empty values.
focus(field)de objetofield: field element object or id Moves the input focus to the given form field.
select(field)de objetofield: field element object or id Selects the value in fields that support text selection
activate(field)de objetofield: 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.

MétodoTipoArgumentosDescrição
serialize(form)de objetoform: 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)de objetoform: form element object or id Returns an Array containing all the input fields in the form.
getInputs(form [, typeName [, name]])de objeto 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)de objetoform: form element object or id Disables all the input fields in the form.
enable(form)de objetoform: form element object or id Enables all the input fields in the form.
focusFirstElement(form)de objetoform: form element object or id Activates the first visible, enabled input field in the form.
reset(form)de objetoform: 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.

MétodoTipoArgumentosDescrição
serialize(element)de objetoelement: element object or id Returns the element's name=value pair, like 'elementName=elementValue'
getValue(element)de objetoelement: 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.

MétodoTipoArgumentosDescrição
inputSelector(element)de objetoelement: 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)de objetoelement: 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)de objetoelement: 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']

The Abstract.TimedObserver

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.

MétodoTipoArgumentosDescrição
[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.
getValue()instance, abstract (nenhum) Derived classes have to implement this method to determine what is the current value being monitored in the element.
registerCallback()de objeto(nenhum) This method is typically not called externally. It is called by the object itself to start monitoring the element.
onTimerEvent()de objeto(nenhum) This method is typically not called externally. It is called by the object itself periodically to check the element.

PropriedadeTipoDescrição
elementObject The 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

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.

MétodoTipoArgumentosDescrição
[ctor](element, frequency, callback)constructor element: element object or id, frequency: interval in seconds, callback: function to be called when the element changes Inherited from Abstract.TimedObserver. Creates an object that will monitor the element's value property.
getValue()de objeto (nenhum) Returns the element's value.

The Form.Observer

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 contais a elements that do not expose an event that reports the value changes. In that case you can use the Form.EventObserver class instead.

MétodoTipoArgumentosDescrição
[ctor](form, frequency, callback)constructor form: form object or id, frequency: interval in seconds, callback: function to be called when any data entry element in the form changes Inherited from Abstract.TimedObserver. Creates an object that will monitor the form for changes.
getValue()de objeto (nenhum) Returns the serialization of all form's data.

The Abstract.EventObserver

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.

MétodoTipoArgumentosDescrição
[ctor](element, callback)constructor element: element object or id, callback: function to be called when the event happens Creates an object that will monitor the element.
getValue()instance, abstract (nenhum) Derived classes have to implement this method to determine what is the current value being monitored in the element.
registerCallback()de objeto(nenhum) This method is typically not called externally. It is called by the object to bind itself to the element's event.
registerFormCallbacks()de objeto(nenhum) 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()de objeto(nenhum) This method is typically not called externally. It will be bound to the element's event.

PropriedadeTipoDescrição
elementObject The 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

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.

MétodoTipoArgumentosDescrição
[ctor](element, callback)constructor element: element object or id, callback: function to be called when the event happens Inherited from Abstract.EventObserver. Creates an object that will monitor the element's value property.
getValue()de objeto (nenhum) Returns the element's value

The Form.EventObserver

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.Observer class instead.

MétodoTipoArgumentosDescrição
[ctor](form, callback)constructor form: form object or id, callback: function to be called when any data entry element in the form changes Inherited from Abstract.EventObserver. Creates an object that will monitor the form for changes.
getValue()de objeto (nenhum) Returns the serialization of all form's data.

The Position object (preliminary documentation)

This object provides a host of functions that help when working with element positioning.

MétodoTipoArgumentosDescrição
prepare()de objeto(nenhum) Adjusts the deltaX and deltaY properties to accomodate changes in the scroll position. Remember to call this method before any calls to withinIncludingScrolloffset after the page scrolls.
realOffset(element)de objetoelement: object Returns 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]
cumulativeOffset(element)de objetoelement: object Returns an Array with the correct positioning offsets of the 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)de objetoelement: object, x and y: coordinates of a point Tests if the given point coordinates are inside the bounding rectangle of the given element
withinIncludingScrolloffsets(element, x, y)de objetoelement: object, x and y: coordinates of a point  
overlap(mode, element)de objetomode: 'vertical' or 'horizontal', element: object 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.10, meaning that the point is at the 10% (30px) mark from the top border of the DIV.
clone(source, target)de objetosource: element object or id, target: element object or id Resizes and repositions the target element identically to the source element.


Se você encontrar erros, informação errada ou incompleta, ou pura e simples tolices, por favor e eu tentarei corrigir o quanto antes.