Anota��es de um desenvolvedor sobre a prototype.js
abrange a vers�o 1.4.0
Sum�rio
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 notou 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.
� medida que voc� ler os exemplos e a refer�ncia, caso voc� tenha familiaridade com a linguagem de progama��o Ruby voc� notar� uma semelhan�a proposital entre as classes constituintes de Ruby e muitas das extens�es implementadas por esta biblioteca.
Artigo relacionado
Advanced JavaScript guide (em ingl�s).
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> P�gina de Teste </TITLE> <script src="prototype-1.4.0.js"></script> <script> function teste1() { var d = $('myDiv'); alert(d.innerHTML); } function teste2() { var divs = $('myDiv','myOtherDiv'); for(i=0; i<divs.length; i++) { alert(divs[i].innerHTML); } } </script> </HEAD> <BODY> <div id="myDiv"> <p>Este � um par�grafo</p> </div> <div id="myOtherDiv"> <p>Outro par�grafo</p> </div> <input type="button" value=Teste1 onclick="teste1();"><br> <input type="button" value=Teste2 onclick="teste2();"><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 teste3()
{
alert( $F('nomeUsuario') );
}
</script>
<input type="text" id="nomeUsuario" value="Jo�o da Silva"><br>
<input type="button" value=Teste3 onclick="teste3();"><br>
Usando a fun��o $A()
A fun��o $A() converte o �nico argumento que ela aceita em um objeto do tipo Array.
Esta fun��o, combinada com as extens�es da classe Array, torna mais f�cil converter ou copiar qualquer lista enumer�vel em um Array. Uma utiliza��o sugerida � para converter objetos do tipo NodeList do DOM em arrays comuns, que podem ser percorridos mais eficientemente. Veja o exemplo a seguir.
<script>
function mostraOpcoes(){
var minhaNodeList = $('lstEmpregados').getElementsByTagName('option');
var nodes = $A(minhaNodeList);
nodes.each(function(node){
alert(node.nodeName + ': ' + node.innerHTML);
});
}
</script>
<select id="lstEmpregados" size="10" >
<option value="5">Buchanan, Steven</option>
<option value="8">Callahan, Laura</option>
<option value="1">Davolio, Nancy</option>
</select>
<input type="button" value="Mostre items da lista" onclick="mostraOpcoes();" >
Usando a fun��o $H()
A fun��o $H() converte objetos em um Hash enumer�vel, que se assemelha a um arrays associativo (lista de pares chave/valor).
<script>
function testarHash()
{
//criando o objeto
var a = {
primeiro: 10,
segundo: 20,
terceiro: 30
};
//transformando-o em um hash
var h = $H(a);
alert(h.toQueryString()); //mostra: primeiro=10&segundo=20&terceiro=30
}
</script>
Usando a fun��o $R()
A fun��o $R() � um atalho para new ObjectRange(limiteInferior, limiteSuperior, excluirLimites).
Siga para a documenta��o da classe ObjectRange onde voc� encontrar� uma explica��o mais abrangente sobre essa classe. Por momento, vamos examinar um exemplo simplificado que tamb�m demonstra o uso de iteradores por meio do m�todo each. Maiores detalhes a respeito desse m�todo podem ser encontrados na documenta��o da classe Enumerable.
<script>
function demoDollar_R(){
var range = $R(10, 20, false);
range.each(function(value, index){
alert(value);
});
}
</script>
<input type="button" value="Contagem" onclick="demoDollar_R();" >
Using the Try.these() function
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 de uma url como http://servidor/app/busca_vendas?empID=1234&ano=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 buscaVendas()
{
var empID = $F('lstEmpregados');
var y = $F('lstAnos');
var url = 'http://servidor/app/busca_vendas';
var pars = 'empID=' + empID + '&ano=' + y;
var myAjax = new Ajax.Request(
url,
{
method: 'get',
parameters: pars,
onComplete: mostraResposta
});
}
function mostraResposta(requisicaoOriginal)
{
//copia o XML retornado para o textarea
$('resultado').value = requisicaoOriginal.responseText;
}
</script>
<select id="lstEmpregados" size="10" onchange="buscaVendas()">
<option value="5">Buchanan, Steven</option>
<option value="8">Callahan, Laura</option>
<option value="1">Davolio, Nancy</option>
</select>
<select id="lstAnos" size="3" onchange="buscaVendas()">
<option selected="selected" value="1996">1996</option>
<option value="1997">1997</option>
<option value="1998">1998</option>
</select>
<br><textarea id=resultado 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: mostraResposta} representa um objeto an�nimo em nota��o literal (conhecida por 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 mostraResposta.
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 mostraResposta 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 dois argumentos, o primeiro ser� o pr�prio objeto XMLHttpRequest (tamb�m chamado de XHR), o segundo argumento ser� o resultado da avalia��o (eval()) do cabe�alho HTTP X-JSON (se houver um presente na resposta). Voc� poder� ent�o utilizar esse o XHR para extrair os dados retornados e possivelmente checar a propriedade status, que informar� o resultado (c�digo) da chamada HTTP. O cabe�alho X-JSON � �til se voc� quiser retornar algum script ou dados formatados em JSON.
Duas outras 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 especificada 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��o mais 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.
Na vers�o 1.4.0 da biblioteca uma nova forma de callback de evento foi introduzida. Se voc� possui c�digo que deve sempre ser executado para um evento espec�fico, n�o importando qual foi a chamada AJAX que causou o evento, ent�o voc� pode utilizar o novo objeto Ajax.Responders.
Suponhamos que voc� necessita mostrar algum indicativo vis�vel de que uma chamada AJAX est� em curso; algo como um GIF animado ou coisa do g�nero. Voc� pode usar duas fun��es de callback, uma para mostrar o GIF quando a primeira chamada se iniciar e outra para escond�-lo quando a �ltima chamada for conclu�da. Veja o exemplo abaixo.
<script>
var callbacksGlobais = {
onCreate: function(){
Element.show('chamadaEmCurso');
},
onComplete: function() {
if(Ajax.activeRequestCount == 0){
Element.hide('chamadaEmCurso');
}
}
};
Ajax.Responders.register(callbacksGlobais);
</script>
<div id='chamadaEmCurso'><img src='macaco_pulando.gif'>Carregando...</div>
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 buscaHTML()
{
var url = 'http://servidor/app/buscaHTML';
var pars = 'algumParametro=ABC';
var myAjax = new Ajax.Updater(
'resposta_aqui',
url,
{
method: 'get',
parameters: pars
});
}
</script>
<input type=button value="Busca HTML" onclick="buscaHTML()">
<div id="resposta_aqui"></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 resposta_aqui apenas ser� preenchido se a opera��o for conclu�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 buscaHTML()
{
var url = 'http://servidor/app/buscaHTML';
var pars = 'algumParametro=ABC';
var myAjax = new Ajax.Updater(
{success: 'placeholder'},
url,
{
method: 'get',
parameters: pars,
onFailure: mostraErro
});
}
function mostraErro(request)
{
alert('Foi mal. Deu pau...');
}
</script>
<input type=button value="Busca HTML" onclick="buscaHTML()">
<div id="resposta_aqui"></div>
Um outro caso interessante � se seu servidor retorna c�digo em JavaScript junto com o 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;. Mas h� um por�m. Os scripts (fun��es e vari�veis declaradas) retornados n�o ser�o inclu�dos no escopo global da p�gina, ou seja, n�o ficar�o vis�veis ao c�digo j� existente. Conforme o nome da op��p evalScripts sugere, os scripts ser�o apenas avaliados. Qual a diferen�a!? Imagine que a resposta recebida seja a seguinte.
<script language="javascript" type="text/javascript">
function faleAlgo(){
alert('Ol�');
}
</script>
<input type=button value="Clique aqui" onclick="faleAlgo()">
Caso voc� j� tenha tentado, voc� j� sabe que isso n�o funciona. A raz�o � que esse bloco de script ser� apenas avaliado, e avali�-lo (com eval() ) n�o criar� uma fun��o chamada faleAlgo. Nada de �til acontecer� com esse script. Para criar essa fun��o n�s precisamos mudar nosso script para que ele crie de fato a fun��o. Veja o exemplo corrigido.
<script language="javascript" type="text/javascript">faleAlgo = function(){ alert('Ol�'); };</script> <input type=button value="Clique aqui" onclick="faleAlgo()">
Perceba que no exemplo acima n�s n�o empregamos a palavra-chave var para declarar a vari�vel (fun��o). Se fiz�ssemos isso a vari�vel/fun��o seria criada mas ficaria de acesso restrito ao escopo do pr�prio bloco de script (pelo menos no IE). Sem usar var a fun��o ser� criada no escopo global, que � nosso objetivo.
Para mais detalhes sobre essa classe, veja e refer�ncia do Ajax.Updater e a refer�ncia das op��es.
Enumerando... Uau! Putz! Oba!
N�s estamos acostumados com os la�os do tipo for. Do tipo, crie seu array, preencha-o com elementos do mesmo tipo, crie uma estrutura de la�o (for, foreach, while, repeat, etc), acesse cada elemento na seq��ncia, usando seu �ndice num�rico, e fa�a algo �til com o elemento.
Se voc� parar pra pensar, quase todas as vezes que voc� usa um array em seu c�digo significa que voc� estar� utilizando aquele array em algum la�o dentro em breve. N�o seria legal se os objetod do tipo array tivessem mais suporte para trabalhar com esses tipos de itera��es? Sim, seria, e muitas linguagens de programa��o possuem funcionalidade desse tipo em seus arrays ou estruturas equivalentes (tais como cole��es, filas e listas).
Bem, acontece que a prototype.js nos d� o objeto Enumerable que implementa uma enormidade de truques para usarmos quando trabalhando com dados iter�veis. A biblioteca vai al�m e extende a classe Array com todos os m�todos de Enumerable.
La�os a la Ruby
Em javascript padr�o, se voc� quiser mostrar sequencialmente os elementos de um array, voc� pode tranq�ilamente escrever algo assim.
<script>
function mostraLisat(){
var simpsons = ['Homer', 'Marge', 'Lisa', 'Bart', 'Meg'];
for(i=0;i<simpsons.length;i++){
alert(simpsons[i]);
}
}
</script>
<input type="button" value="Mostrar Lista" onclick="mostraLista();" >
Com nosso novo melhor amigo, prototype.js, n�s podemos reescrever esse la�o assim.
function mostraLista(){
var simpsons = ['Homer', 'Marge', 'Lisa', 'Bart', 'Meg'];
simpsons.each( function(familyMember){
alert(familyMember);
});
}
Voc� provavelmente est� pensando "grande coisa... apenas uma sintaxe esquisita para a mesma coisa de sempre". Bem, no exemplo acima, sim, n�o tem nada de espetacular ocorrendo. Afinal n�o h� muito o que ser mudado num exemplo t�o simpl�rio como esse. Mas siga lendo apesar de tudo.
Antes de prosseguirmos... Voc� viu essa fun��o sendo passada como argumento do m�todo each? Vamos come�ar a nos referir a ela como fun��o iteradora.
Seus arrays bombados
Tal como mencionamos acima, � muito comum que todos os elementos de seu array sejam de um mesmo tipo, com as mesmas propriedades e m�todos. Vejamos como podemos tirar proveito de fun��es iteradoras com nossos novos arrays envenenados.
Encontrando um elemento de acordo com um crit�rio de busca.
<script>
function encontreEmpregadoPorID(emp_id){
var listBox = $('lstEmpregados')
var opcoes = listBox.getElementsByTagName('option');
opcoes = $A(opcoes);
var opt = opcoes.find( function(empregado){
return (empregado.value == emp_id);
});
alert(opt.innerHTML); //mostra o nome do empregado
}
</script>
<select id="lstEmpregados" size="10" >
<option value="5">Buchanan, Steven</option>
<option value="8">Callahan, Laura</option>
<option value="1">Davolio, Nancy</option>
</select>
<input type="button" value="Ache Laura" onclick="encontreEmpregadoPorID(8);" >
Agora vamos ao pr�ximo passo. Vamos ver como podemos filtrar items dos arrays e depois retornar apenas um membro de cada elemento.
<script>
function mostreLinksLocais(paragrafo){
paragrafo = $(paragrafo);
var links = $A(paragrafo.getElementsByTagName('a'));
//vamos achar os links que t�m rel="local"
var linksLocais = links.findAll( function(link){
var rel = link.getAttribute("rel");
return rel =='local';
});
//agora vamos extrair o texto de cada link
var textos = linksLocais.pluck('innerHTML');
//vamos colocar os textos em uma �nica string
var resultado = textos.inspect();
alert(resultado);
}
</script>
<p id="algumTexto">
Este <a href="http://othersite.com/page.html">texto</a> tem
<a rel"local" ref="#localAnchor">v�rios</a>
<a rel"local" href="#otherAnchor">links</a>. Alguns s�o
<a href="http://wherever.com/page.html">externos</a>
e alguns s�o <a rel"local" href="#someAnchor">locais</a>
</p>
<input type=button value="Encontre Links Locais" onclick="mostreLinksLocais('algumTexto')">
S� � preciso um pouco de pr�tica para ficar completamente viciado nessa sintaxe. D� uma olhada nas refer�ncias de Enumerable e Array para ver uma lista de todas as fun��es dispon�veis.
Livros que eu recomendo
H� livros que s�o t�o bons que n�o d� pra deixar de recomendar. Os livros abaixo me ajudaram enormemente a aprender as novas t�cnicas necess�rias para se construir uma aplica��o AJAX e tamb�m consolidaram as t�cnicas que eu achava que j� dominava. Eu acredito que um bom livro � um dinheiro bem gasto. � um investimento que se paga e continua a se pagar por um bom tempo.
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�todo | Tipo | Argumentos | Descri��o |
|---|---|---|---|
| extend(destination, source) | est�tico | destination: 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. |
| inspect(targetObj) | est�tico | targetObj: qualquer objeto | Retorna uma string leg�vel que representa targetObj. Caso o objeto passado n�o implemente um m�todo inspect ent�o a fun��o retornar� toString. |
Extens�es da classe Number
| M�todo | Tipo | Argumentos | Descri��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. |
| succ() | de objeto | (nenhum) | Retorna o pr�ximo n�mero. Esse m�todo � comumente utilizado em contextos que envolvem itera��es. |
| times(iterator) | de objeto | iterator: uma fun��o com assinatura equivalente a Function(valor, indice) | Executa a fun��o iterator repetidamente, passando os par�metros valor e indice contendo o valor da vez na itera��o e o �ndice da vez, respectivamente. |
O exemplo a seguir mostrar� mensagens com os n�meros de 0 a 9.
<script>
function usandoTimes(){
var n = 10;
n.times(function(valor, indice){
alert(indice);
});
/***************************
* Tambem daria certo assim:
* (10).times( .... );
***************************/
}
</script>
<input type=button value="Testar Number.times()" onclick="usandoTimes()">
Extens�es da classe Function
| M�todo | Tipo | Argumentos | Descri��o |
|---|---|---|---|
| bind(object) | de objeto | object: 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 objeto | object: 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, mensagem) {
this.chkBox = $(chkBox);
this.mensagem = mensagem;
//ligando nosso metodo ao evento
this.chkBox.onclick =
this.mostraMensagem.bindAsEventListener(this);
},
mostraMensagem: function(evt) {
alert(this.mensagem + ' (' + evt.type + ')');
}
};
var watcher = new CheckboxWatcher('myChk', 'Mudou');
</script>
Extens�es da classe String
| M�todo | Tipo | Argumentos | Descri��o |
|---|---|---|---|
| stripTags() | de objeto | (nenhum) | Retorna a string subtraindo quaisquer tags HTML ou XML. |
| stripScripts() | de objeto | (nenhum) | Retorna a string, subtraindo quaisquer blocos <script />. |
| escapeHTML() | de objeto | (nenhum) | Retorna a string dando escape em quaisquer caracteres de marca��o HTML. |
| unescapeHTML() | de objeto | (nenhum) | A opera��o reversa de escapeHTML() |
| extractScripts() | de objeto | (nenhum) | Retorna um objeto Array com mtodos os blocos <script /> encontrados na string. |
| evalScripts() | de objeto | (nenhum) | Avalia todos os blocos <script /> encontrados na string. |
| toQueryParams() | de objeto | (nenhum) | Separa a string em um array associativo indexado pelo nome de cada parametro (tal como um hash). |
| parseQuery() | de objeto | (nenhum) | Mesmo que toQueryParams(). |
| toArray() | de objeto | (nenhum) | Retrorna um Array com cada caractere da string. |
| camelize() | de objeto | (nenhum) | Converte um string-separada-por-h�fens em uma stringFormatadaComCamelCase. Essa fun��o pode ser �til quando se lida com propriedades de estilo, por exemplo. |
Extens�es da classe Array
De cara, a classe Array extende Enumerable, ent�o todos aqueles m�todos �teis de Enumerable est�o dispon�veis. Alem destes, os m�todos a seguir tamb�m est�o inclu�dos.
| M�todo | Tipo | Argumentos | Descri��o |
|---|---|---|---|
| clear() | de objeto | (nenhum) | Esvazia o array e retorna-o. |
| first() | de objeto | (nenhum) | Retorna o primeiro elemento do array. |
| last() | de objeto | (nenhum) | Retorna o �ltimo elemento do array. |
| compact() | de objeto | (nenhum) | Retorna o array sem os elementos que sejam null ou undefined. Este m�todo n�o altera o array original, apenas retorna um novo. |
| flatten() | de objeto | (nenhum) | Retorna uma vers�o unidimensional (achatada) do array. Esse achatamento ocorre porque cada elemento do array que tamb�m � um array ter� seus elementos inclu�dos no array-pai. Esse processo ocorre de forma recursiva para cada elemento. |
| without(valor1 [, valor2 [, .. valorN]]) | de objeto | valor1 ... valorN: valores a serem exclu�dos se encontrados no array. | Retorna o array subtraindo os elementos listados como argumentos. |
| indexOf(valor) | de objeto | valor: o valor procurado. | Retorna o �ndice, baseado em zero, do primeiro elemento encontrado com o valor. Retorna -1 se nenhuma ocorr�ncia for encontrada. |
| reverse([alterarOriginal]) | de objeto | alterarOriginal: indica se o array original ser� revertido. | Retorna o array em ordem reversa. Se nenhum argumento for dado ou se o argumento for true ent�o o array original tamb�m ser� revertido. Caso contr�rio ele permanecer� do jeito que est�. |
| shift() | de objeto | (nenhum) | Retorna o primeiro elemento do array e retira-o do array, reduzindo o tamanho do array em 1 elemento. |
| inspect() | de objeto | (nenhum) | Retorna uma string com os elementos do array. |
Extens�es do objeto document do DOM
| M�todo | Tipo | Argumentos | Descri��o |
|---|---|---|---|
| getElementsByClassName(nomeDaClasse [, elementoPai]) | de objeto | nomeDaClasse: nome da clase CSS associada com os elementos, elementoPai: objeto ou id do elemento que cont�m os elementos a serem buscados. | Retorna todos os elementos com a classe CSS informada. Se o elemento-pai n�o for dado, ent�o os elementos ser�o procurados dentro do elemento body. |
Extens�es do objeto Event
| Propriedade | Tipo | Descri��o |
|---|---|---|
| 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. |
| M�todo | Tipo | Argumentos | Descri��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>
Novos objetos e classes definidos em prototype.js
Outra forma que a biblioteca ajuda � ao disponibilizar diversos objetos que implementam suporte a design orientado a objetos e tamb�m funcionalidades de uso geral.
The PeriodicalExecuter object
This object provides the logic for calling a given function repeatedly, at a given interval.
| M�todo | Tipo | Argumentos | Descri��o |
|---|---|---|---|
| [ctor](callback, interval) | constructor | callback: a parameterless function, interval: number of seconds | Creates one instance of this object that will call the function repeatedly. |
| Propriedade | Tipo | Descri��o |
|---|---|---|
| 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.
| Propriedade | Tipo | Descri��o |
|---|---|---|
| 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.
//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�todo | Tipo | Argumentos | Descri��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�todo | Tipo | Argumentos | Descri��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�todo | Tipo | Argumentos | Descri��o |
|---|---|---|---|
| setOptions(options) | de objeto | options: 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
| Propriedade | Tipo | Tipo | Descri��o |
|---|---|---|---|
| Events | Array | est�tico | List of possible events/statuses reported during an AJAX operation. The list contains: 'Uninitialized', 'Loading', 'Loaded', 'Interactive', and 'Complete.' |
| transport | XMLHttpRequest | de objeto | The XMLHttpRequest object that carries the AJAX operation |
| M�todo | Tipo | Argumentos | Descri��o |
|---|---|---|---|
| [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) | de objeto | url: 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 objeto | 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.
| Propriedade | Tipo | Default | Descri��o |
|---|---|---|---|
| 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'] |
| 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
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.
| Propriedade | Tipo | Tipo | Descri��o |
|---|---|---|---|
| ScriptFragment | String | est�tico | A regular expression to identify scripts |
| containers | Object | de objeto | This object contains two properties: containers.success will be used when the AJAX call succeeds, and containers.failure will be used otherwise. |
| M�todo | Tipo | Argumentos | Descri��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.
| Propriedade | Tipo | Tipo | Descri��o |
|---|---|---|---|
| container | Object | de objeto | This value will be passed straight to the Ajax.Updater's constructor. |
| url | String | de objeto | This value will be passed straight to the Ajax.Updater's constructor. |
| frequency | Number | de 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 |
| decay | Number | de objeto | Keeps the current decay level applied when re-executing the task |
| updater | Ajax.Updater | de objeto | The most recently used Ajax.Updater object |
| timer | Object | de objeto | The JavaScript timer being used to notify the object when it is time for the next refresh. |
| M�todo | Tipo | Argumentos | Descri��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�todo | Tipo | Argumentos | Descri��o |
|---|---|---|---|
| toggle(elem1 [, elem2 [, elem3 [...]]]) | de objeto | elemN: element object or id | Toggles the visibility of each passed element. |
| hide(elem1 [, elem2 [, elem3 [...]]]) | de objeto | elemN: element object or id | Hides each element bu setting its style.display to 'none'. |
| show(elem1 [, elem2 [, elem3 [...]]]) | de objeto | elemN: element object or id | Shows each element bu resetting its style.display to ''. |
| remove(element) | de objeto | element: element object or id | Removes the element from the document. |
| getHeight(element) | de objeto | element: element object or id | Returns the offsetHeight of the element |
| addClassName(element, className) | de objeto | 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) | de objeto | 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) | de objeto | element: element object or id, className: name of a CSS class | Removes the given class name from the element's class names. |
| cleanWhitespace(element) | de objeto | 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
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�todo | Tipo | Argumentos | Descri��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. |
| Propriedade | Tipo | Tipo | Descri��o |
|---|---|---|---|
| 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 | de objeto | The element object that the insertion will be made relative to. |
| content | String | de 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�todo | Tipo | Argumentos | Descri��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�todo | Tipo | Argumentos | Descri��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�todo | Tipo | Argumentos | Descri��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�todo | Tipo | Argumentos | Descri��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�todo | Tipo | Argumentos | Descri��o |
|---|---|---|---|
| clear(field1 [, field2 [, field3 [...]]]) | de objeto | fieldN: field element object or id | Clears the value of each passed form field element. |
| present(field1 [, field2 [, field3 [...]]]) | de objeto | fieldN: field element object or id | Returns true only if all forms fields contain non-empty values. |
| focus(field) | de objeto | field: field element object or id | Moves the input focus to the given form field. |
| select(field) | de objeto | field: field element object or id | Selects the value in fields that support text selection |
| activate(field) | de objeto | 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.
| M�todo | Tipo | Argumentos | Descri��o |
|---|---|---|---|
| serialize(form) | de objeto | 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) | de objeto | form: 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 objeto | form: form element object or id | Disables all the input fields in the form. |
| enable(form) | de objeto | form: form element object or id | Enables all the input fields in the form. |
| focusFirstElement(form) | de objeto | form: form element object or id | Activates the first visible, enabled input field in the form. |
| reset(form) | de objeto | 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.
| M�todo | Tipo | Argumentos | Descri��o |
|---|---|---|---|
| serialize(element) | de objeto | element: element object or id | Returns the element's name=value pair, like 'elementName=elementValue' |
| getValue(element) | de objeto | 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.
| M�todo | Tipo | Argumentos | Descri��o |
|---|---|---|---|
| inputSelector(element) | de objeto | 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'] |
| textarea(element) | de objeto | 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'] |
| select(element) | de objeto | 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'] |
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�todo | Tipo | Argumentos | Descri��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. |
| Propriedade | Tipo | Descri��o |
|---|---|---|
| element | Object | The element object that is being monitored. |
| frequency | Number | This is actually the interval in seconds between checks. |
| callback | Function(Object, String) | The function to be called whenever the element changes. It will receive the element object and the new value. |
| lastValue | String | The 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�todo | Tipo | Argumentos | Descri��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�todo | Tipo | Argumentos | Descri��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�todo | Tipo | Argumentos | Descri��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. |
| Propriedade | Tipo | Descri��o |
|---|---|---|
| element | Object | The element object that is being monitored. |
| callback | Function(Object, String) | The function to be called whenever the element changes. It will receive the element object and the new value. |
| lastValue | String | The 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�todo | Tipo | Argumentos | Descri��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�todo | Tipo | Argumentos | Descri��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�todo | Tipo | Argumentos | Descri��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 objeto | element: 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 objeto | element: 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 objeto | element: 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 objeto | element: object, x and y: coordinates of a point | |
| overlap(mode, element) | de objeto | mode: '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 objeto | source: 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.




