anotações de um desenvolvedor sobre a prototype

Upload: alexandre

Post on 10-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    1/25

    Anotaes de um desenvolvedor sobre a prototype.jsa b r a n g e a v e r s o 1 . 4 . 0

    por Sergio Pereiraltima atualizao : 16 de abril de 2006

    Outros idiomas

    SumrioO que isso? Artigo relacionado As funes utilitrias Utilizando a funo $() Usando a funo $F() Usando a

    funo $A() Usando a funo $H() Usando a funo $R() Using the Try.these() function O objeto Ajax Utilizando a classe Ajax.Request Utilizando a classe Ajax.Updater Enumerando... Uau! Putz! Oba! Laos a laRuby Seus arrays bombados Livros que eu recomendo Referncia da prototype.js Extenses das classesJavaScript Extenses da classe Object Extenses da classe Number Extenses da classe Function Extenses daclasse String Extenses da classe Array Extenses do objeto document do DOM Extenses do objeto Event Novos objetos e classes definidos em prototype.js The PeriodicalExecuter object The Prototype object TheClass object The Ajax.Base The Ajax.Request The options argument object The Ajax.Updater TheAjax.PeriodicalUpdater The Element object The Abstract object The Abstract.Insertion The Insertion object The Insertion.Before The Insertion.Top The Insertion.Bottom The Insertion.After The Field object The Form object The Form.Element object The Form.Element.Serializers object TheAbstract.TimedObserver The Form.Element.Observer The Form.Observer The Abstract.EventObserver The Form.Element.EventObserver The Form.EventObserver The Position object (preliminary documentation)

    O que isso?Caso voc ainda no tenha tido a oportunidade de utiliz-la, prototype.js uma tima biblioteca javascriptescrita por Sam Stephenson . Esta coleo de funes impressionantemente bem escrita e bem pensada,utiliza tcnicas de acordo com os padres atuais e alivia seu trabalho na hora de produzir as pginasaltamente interativas que caracterizam a chamada Web 2.0.Se voc andou tentando utilizar essa biblioteca recentemente, voc provavelmente notou que adocumentao no pode ser considerada um de seus pontos fortes. Tal como muitos outros programadoresfizeram, eu tambm s sonsegui entender como utilizar a prototype.js ao inspecionar seu cdigo-fonte. Euimaginei que poderia ser til se eu fizesse algumas anotaes enquanto eu aprendia e ento compartilhassecom todo mundo.Tambm estou incluindo aqui uma referncia no-oficial para os objetos, classes, funes e extensesimplementadas nessa biblioteca. medida que voc ler os exemplos e a referncia, caso voc tenha familiaridade com a linguagem deprogamao Ruby voc notar uma semelhana proposital entre as classes constituintes de Ruby e muitas dasextenses implementadas por esta biblioteca.

    sumrio

    Artigo relacionadoAdvanced JavaScript guide (em ingls).

    sumrio

    As funes utilitriasA biblioteca vm com diversos objetos pr-definidos e funes utilitrias. O objetivo claro dessas funes evitar uma imensido de digitao repetitiva e propensa a erros, que eu costumo comparar a musculao.

    sumrio

    Utilizando a funo $()A funo $() um conveniente atalho para as inmeras ocorrncias da chamada funodocument.getElementById() do DOM. Tal como a funo do DOM, esta retorna o elemento que identificado pelo valor id passado como argumento.No entanto, diferentemente da funo do DOM, essa vai mais alm. Voc pode passar mais de um argumentoe a funo $() retornar um objeto Array com todos os elementos requisitados. O exemplo a seguir ilustraesse fato.

    http://prototype.conio.net/mailto:[email protected]://www.sergiopereira.com/articles/prototype.js.htmlhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Whatsthat%23Whatsthathttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#RelatedArticle%23RelatedArticlehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#UtilityFunctions%23UtilityFunctionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#DollarFunction%23DollarFunctionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#DollarFunction%23DollarFunctionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#DollarFunction%23DollarFunctionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_F_Function%23Dollar_F_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_F_Function%23Dollar_F_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_F_Function%23Dollar_F_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_A_Function%23Dollar_A_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_A_Function%23Dollar_A_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_A_Function%23Dollar_A_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_A_Function%23Dollar_A_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_H_Function%23Dollar_H_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_H_Function%23Dollar_H_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_H_Function%23Dollar_H_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_R_Function%23Dollar_R_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_R_Function%23Dollar_R_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_R_Function%23Dollar_R_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#TryThese%23TryThesehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#TryThese%23TryThesehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#TryThese%23TryThesehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#UsingAjax%23UsingAjaxhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#UsingAjax%23UsingAjaxhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#UsingAjax%23UsingAjaxhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#UsingAjaxRequest%23UsingAjaxRequesthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#UsingAjaxRequest%23UsingAjaxRequesthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#UsingAjaxRequest%23UsingAjaxRequesthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#UsingAjaxUpdater%23UsingAjaxUpdaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#UsingAjaxUpdater%23UsingAjaxUpdaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#UsingAjaxUpdater%23UsingAjaxUpdaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Enumerating%23Enumeratinghttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Loops%23Loopshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Loops%23Loopshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#EnumeratingArrays%23EnumeratingArrayshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Books%23Bookshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference%23Referencehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions%23Reference.Extensionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions%23Reference.Extensionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.Object%23Reference.Extensions.Objecthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.Object%23Reference.Extensions.Objecthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.Number%23Reference.Extensions.Numberhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.Number%23Reference.Extensions.Numberhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.Function%23Reference.Extensions.Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.Function%23Reference.Extensions.Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.String%23Reference.Extensions.Stringhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.String%23Reference.Extensions.Stringhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.String%23Reference.Extensions.Stringhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Array%23Reference.Arrayhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Array%23Reference.Arrayhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.DOM%23Reference.Extensions.DOMhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.DOM%23Reference.Extensions.DOMhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.DOM%23Reference.Extensions.DOMhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.Event%23Reference.Extensions.Eventhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.Event%23Reference.Extensions.Eventhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.NewObjects%23Reference.NewObjectshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.PeriodicalExecuter%23Reference.PeriodicalExecuterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.PeriodicalExecuter%23Reference.PeriodicalExecuterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.PeriodicalExecuter%23Reference.PeriodicalExecuterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Prototype%23Reference.Prototypehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Prototype%23Reference.Prototypehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Prototype%23Reference.Prototypehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Enumerable%23Reference.Enumerablehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Enumerable%23Reference.Enumerablehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Enumerable%23Reference.Enumerablehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Enumerable%23Reference.Enumerablehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Enumerable%23Reference.Enumerablehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Base%23Ajax.Basehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Base%23Ajax.Basehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Base%23Ajax.Basehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Request%23Ajax.Requesthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Request%23Ajax.Requesthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Request%23Ajax.Requesthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.optionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.optionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.optionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Updater%23Ajax.Updaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Updater%23Ajax.Updaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Updater%23Ajax.Updaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.PeriodicalUpdater%23Ajax.PeriodicalUpdaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.PeriodicalUpdater%23Ajax.PeriodicalUpdaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Element%23Elementhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Element%23Elementhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Element%23Elementhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract%23Abstracthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract%23Abstracthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract%23Abstracthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion%23Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion%23Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion%23Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion%23Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.Before%23Insertion.Beforehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.Before%23Insertion.Beforehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.Before%23Insertion.Beforehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.Top%23Insertion.Tophttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.Top%23Insertion.Tophttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.Top%23Insertion.Tophttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.Bottom%23Insertion.Bottomhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.Bottom%23Insertion.Bottomhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.Bottom%23Insertion.Bottomhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.After%23Insertion.Afterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.After%23Insertion.Afterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.After%23Insertion.Afterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Field%23Fieldhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Field%23Fieldhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Field%23Fieldhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Field%23Fieldhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form%23Formhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form%23Formhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form%23Formhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element%23Form.Elementhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element%23Form.Elementhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element%23Form.Elementhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.Serializers%23Form.Element.Serializershttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.Serializers%23Form.Element.Serializershttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.Serializers%23Form.Element.Serializershttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.TimedObserver%23Abstract.TimedObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.TimedObserver%23Abstract.TimedObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.Observer%23Form.Element.Observerhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.Observer%23Form.Element.Observerhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.Observer%23Form.Element.Observerhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Observer%23Form.Observerhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Observer%23Form.Observerhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Observer%23Form.Observerhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.EventObserver%23Abstract.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.EventObserver%23Abstract.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.EventObserver%23Abstract.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.EventObserver%23Form.Element.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.EventObserver%23Form.Element.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Observer%23Form.Observerhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Observer%23Form.Observerhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Observer%23Form.Observerhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Position%23Positionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Position%23Positionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Position%23Positionhttp://prototype.conio.net/http://www.conio.net/http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference%23Referencehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/advjs.htmlhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tocmailto:[email protected]://www.sergiopereira.com/articles/prototype.js.htmlhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Whatsthat%23Whatsthathttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#RelatedArticle%23RelatedArticlehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#UtilityFunctions%23UtilityFunctionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#DollarFunction%23DollarFunctionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_F_Function%23Dollar_F_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_A_Function%23Dollar_A_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_A_Function%23Dollar_A_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_H_Function%23Dollar_H_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Dollar_R_Function%23Dollar_R_Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#TryThese%23TryThesehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#UsingAjax%23UsingAjaxhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#UsingAjaxRequest%23UsingAjaxRequesthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#UsingAjaxUpdater%23UsingAjaxUpdaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Enumerating%23Enumeratinghttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Loops%23Loopshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Loops%23Loopshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#EnumeratingArrays%23EnumeratingArrayshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Books%23Bookshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference%23Referencehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions%23Reference.Extensionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions%23Reference.Extensionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.Object%23Reference.Extensions.Objecthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.Number%23Reference.Extensions.Numberhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.Function%23Reference.Extensions.Functionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.String%23Reference.Extensions.Stringhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.String%23Reference.Extensions.Stringhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Array%23Reference.Arrayhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.DOM%23Reference.Extensions.DOMhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Extensions.Event%23Reference.Extensions.Eventhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.NewObjects%23Reference.NewObjectshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.PeriodicalExecuter%23Reference.PeriodicalExecuterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Prototype%23Reference.Prototypehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Enumerable%23Reference.Enumerablehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Enumerable%23Reference.Enumerablehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Base%23Ajax.Basehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Request%23Ajax.Requesthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.optionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Updater%23Ajax.Updaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.PeriodicalUpdater%23Ajax.PeriodicalUpdaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.PeriodicalUpdater%23Ajax.PeriodicalUpdaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Element%23Elementhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract%23Abstracthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion%23Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion%23Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.Before%23Insertion.Beforehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.Top%23Insertion.Tophttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.Bottom%23Insertion.Bottomhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Insertion.After%23Insertion.Afterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Field%23Fieldhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Field%23Fieldhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form%23Formhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element%23Form.Elementhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.Serializers%23Form.Element.Serializershttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.TimedObserver%23Abstract.TimedObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.TimedObserver%23Abstract.TimedObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.Observer%23Form.Element.Observerhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Observer%23Form.Observerhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.EventObserver%23Abstract.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.EventObserver%23Form.Element.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.EventObserver%23Form.Element.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Observer%23Form.Observerhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Position%23Positionhttp://prototype.conio.net/http://www.conio.net/http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference%23Referencehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/advjs.htmlhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://prototype.conio.net/
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    2/25

    Pgina de Teste

    function teste1(){

    var d = $('myDiv');alert(d.innerHTML);

    }

    function teste2(){

    var divs = $('myDiv','myOtherDiv');for(i=0; i

  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    3/25

    function mostraOpcoes(){var minhaNodeList = $('lstEmpregados').getElementsByTagName('option');var nodes = $A(minhaNodeList);

    nodes.each(function(node){alert(node.nodeName + ': ' + node.innerHTML);

    });}

    Buchanan, StevenCallahan, LauraDavolio, Nancy

    sumrio

    Usando a funo $H()A funo $H() converte objetos em um Hash enumervel, que se assemelha a um arrays associativo (lista depares chave/valor).

    function testarHash(){

    //criando o objetovar a = {

    primeiro: 10,segundo: 20,terceiro: 30};

    //transformando-o em um hashvar h = $H(a);alert(h.toQueryString()); //mostra: primeiro=10&segundo=20&terceiro=30

    }

    sumrio

    Usando a funo $R()A funo $R() um atalho para new ObjectRange(limiteInferior, limiteSuperior,

    excluirLimites) .Siga para a documentao da classe ObjectRange onde voc encontrar uma explicao mais abrangentesobre essa classe. Por momento, vamos examinar um exemplo simplificado que tambm demonstra o uso deiteradores por meio do mtodo each . Maiores detalhes a respeito desse mtodo podem ser encontrados nadocumentao da classe Enumerable .

    function demoDollar_R(){

    var range = $R(10, 20, false);range.each(function(value, index){

    alert(value);});

    }

    sumrio

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Hash%23Reference.Hashhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.ObjectRange%23Reference.ObjectRangehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Enumerable%23Reference.Enumerablehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Hash%23Reference.Hashhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.ObjectRange%23Reference.ObjectRangehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Enumerable%23Reference.Enumerablehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23toc
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    4/25

    Using the Try.these() function

    Utilizando a funo Try.these()A funo Try.these() facilita as coisas na hora que se torna necessrio experimentar diferentes chamadasa funes at que uma funcione. Esta funo aceita uma lista de chamadas a outras funes comoargumento. Ento cada chamada executada na ordem dada, at que uma d certo e ento o resultadodessa chamada retornado.No exemplo a seguir, a propriedade xmlNode.text funciona em alguns browsers, exmlNode.textContent funciona em outros browsers. Ao utilizarmos a funo Try.these() ns podemos

    sempre retornar a chamada que funciona corretamente (sem erros).function getXmlNodeValue(xmlNode){

    return Try.these(function() {return xmlNode.text;},function() {return xmlNode.textContent;));

    }

    sumrio

    O objeto AjaxT bem, as funes utilitrias mencionadas acima so legais mas convenhamos, elas tambm no so a coisamais avanada que j se viu, no ? Voc provavelmente poderia ter escrito essas funes sozinho ou talvezat voc j tenha algumas funes semelhantes em seus prprios scripts. S que essas funes so apenas aponta do iceberg.Eu tenho certeza que seu interesse pela prototype.js advm principalmente de suas capacidades relacionadasa AJAX. Ento vamos explicar como a biblioteca facilita as coisas pra voc quando necessrio implementaroperaes de AJAX.O objeto Ajax pr-definido na biblioteca, criado para encapsular e simplificar o cdigo traioeiro que necessrio quando se implementam funcionalidades AJAX. Este objeto contm uma srie de classes quedisponibilizam lgica AJAX. Vamos dar uma olhada em algumas desas classes.

    sumrio

    Utilizando a classe Ajax.RequestSe voc no estiver utilizando nenhuma biblioteca auxiliar, voc provavelmente est escrevendo umamontanha de cdigo para criar um objeto XMLHttpRequest , acompanhar seu progresso assincronamente, eento extrair a resposta e process-la. Considere-se um sortudo se voc no precisa suportar mais de um tipode browser.Para auxiliar com operaes AJAX, a biblioteca define a classe Ajax.Request .Digamos que voc tenha uma aplicao que pode se comunicar com o servidor atravs de uma url comohttp://servidor/app/busca_vendas?empID=1234&ano=1998 , que retorna uma resposta em XML similar seguinte.

    12341998-01$8,115.36

    12341998-02

    $11,147.51

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://en.wikipedia.org/wiki/Ajax_(programming)http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://en.wikipedia.org/wiki/Ajax_(programming)http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23toc
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    5/25

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

    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;

    }

    Buchanan, StevenCallahan, LauraDavolio, Nancy

    199619971998


    D para voc perceber o segundo parmetro passado ao contrutor do objeto Ajax.Request ? O parmetro{method: 'get', parameters: pars, onComplete: mostraResposta} representa um objetoannimo em notao literal (conhecida por JSON). O que ele significa que estamos passando um objeto quetem uma propriedade chamada method que contm a string 'get' , uma outra propriedade chamada

    parameters que contm a querystring da requisio HTTP, e uma propriedade/mtodo onCompletecontendo a funo mostraResposta .Ainda h mais algumas propriedades que voc pode definir nesse objeto, tais como asynchronous , quepode ser true ou false e determina se a chamada AJAX ao servidor ser feita de maneira assncrona ouno (o valor default true .)Este parmetro define as opes para a chamada AJAX. Em nosso exemplo estamos chamando a url doprimeiro argumento atravs de um comando HTTP GET, passando a querystring contida na varivel pars , e oobjeto Ajax.Request ir chamar a funo mostraResposta quando terminar de buscar receber aresposta.Como se sabe, o objeto XMLHttpRequest anuncia o progresso durante a chamada HTTP. Este progressopode representar quatro diferentes estgios: Loading (carregando), Loaded (carregado), Interactive(interativo), or Complete (completo). Voc pode fazer com que o objeto Ajax.Request chame uma funosua em cada um desses estgios, sendo o Complete o mais comum. Para especificar a funo para o objeto,basta utilizar propriedades/mtodos chamados onXXXXXnas opes da chamada, tal como a propriedade

    onComplete em nosso exemplo anterior. A funo especificada ser chamada pelo objeto com doisargumentos, o primeiro ser o prprio objeto XMLHttpRequest (tambm chamado de XHR), o segundoargumento ser o resultado da avaliao (eval()) do cabealho HTTP X-JSON (se houver um presente naresposta). Voc poder ento utilizar esse o XHR para extrair os dados retornados e possivelmente checar apropriedade status , que informar o resultado (cdigo) da chamada HTTP. O cabealho X-JSON til sevoc quiser retornar algum script ou dados formatados em JSON.

  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    6/25

    Duas outras opes interessantes podem ser utilizadas para processar os resultados. Ns podemos especificara opo onSuccess como uma funo a ser chamada quando a chamada AJAX executa sem erros.Analogamente, a opo onFailure pode ser especificada como uma funo a ser chamada quando um erroocorrer durante a chamada. Tal como as funes onXXXXX, essas duas funes tambm sero chamadas comum argumento que conter o objeto XMLHttpRequest que serviu de veculo para a chamada AJAX.Nosso exemplo no fez nenhum processamento interessante da resposta XML. Ns apenas ecoamos o XML notextarea. Uma utilizao mais tpica da resposta iria provavelmente extrair a informao desejada de dentrodo XML e atualizar alguns elementos da pgina, ou talvez mesmo utilizar uma transformao XSLT para criarHTML e inserir na pgina.Na verso 1.4.0 da biblioteca uma nova forma de callback de evento foi introduzida. Se voc possui cdigoque deve sempre ser executado para um evento especfico, no importando qual foi a chamada AJAX quecausou o evento, ento voc pode utilizar o novo objeto Ajax.Responders .Suponhamos que voc necessita mostrar algum indicativo visvel de que uma chamada AJAX est em curso;algo como um GIF animado ou coisa do gnero. Voc pode usar duas funes de callback, uma para mostraro GIF quando a primeira chamada se iniciar e outra para escond-lo quando a ltima chamada for concluda.Veja o exemplo abaixo.

    var callbacksGlobais = {

    onCreate: function(){Element.show('chamadaEmCurso');

    },

    onComplete: function() {if(Ajax.activeRequestCount == 0){

    Element.hide('chamadaEmCurso');}

    }};

    Ajax.Responders.register(callbacksGlobais);

    Carregando...

    Para maiores detalhes, d uma olhada na referncia do Ajax.Request e na referncia das opes . sumrio

    Utilizando a classe Ajax.UpdaterSupondo que voc tenha uma URL no seu servidor que possa retornar os dados j formatados em HTML,ento a biblioteca facilita ainda mais sua vida com a classe Ajax.Updater . Com ela basta voc informarqual o elemento que deve ser preenchido com o HTML que ser retornado pela chamada AJAX. Um exemplodemonstra isso melhor do que eu conseguiria descrever.

    function buscaHTML(){

    var url = 'http://servidor/app/buscaHTML';var pars = 'algumParametro=ABC';

    var myAjax = new Ajax.Updater('resposta_aqui',url,{

    method: 'get',parameters: pars

    });

    }

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Responders%23Ajax.Respondershttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Request%23Ajax.Requesthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.optionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Responders%23Ajax.Respondershttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Request%23Ajax.Requesthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.optionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23toc
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    7/25

    Como voc pode ver, o cdigo muito semelhante ao exemplo anterior, excluindo-se a funo onCompletee passando-se o id do elemento no construtor. Vamos alterar um pouco o cdigo para ilustrar como possveltratar erros produzidos no servidor em seu cdigo no cliente.Vamos incluir mais opes na chamada, especificando uma funo para capturar situaes de erro. Isso se fazcom o auxlio da opo onFailure . Vamos tambm especificar que o elemento de id resposta_aquiapenas ser preenchido se a operao for concluda com sucesso. Para que isso seja possvel, vamos mudar oprimeiro parametro de um simples id de elemento para um objeto. O construtor de Ajax.Updater aceitatambm como primeiro parmetro um objeto com duas propriedades, success (a ser usado quando tudotermina bem) e failure (a ser usado quando um erro ocorre na chamada). No nosso caso no precisaremosda propriedade failure pois estaremos usando uma funo nossa para tratar o erro. A funo

    reportError tratar o erro conforme especificado na opo onFailure .

    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...');}

    Um outro caso interessante se seu servidor retorna cdigo em JavaScript junto com o HTML. O objeto Ajax.Updater pode avaliar o cdigo JavaScript. Para fazer o objeto tratar a resposta do servidor como

    JavaScript, basta que voc use a opo evalScripts: true; . Mas h um porm. Os scripts (funes evariveis declaradas) retornados no sero includos no escopo global da pgina, ou seja, no ficaro visveisao cdigo j existente. Conforme o nome da opp evalScripts sugere, os scripts sero apenasavaliados . Qual a diferena!? Imagine que a resposta recebida seja a seguinte.

    function faleAlgo(){

    alert('Ol');}

    Caso voc j tenha tentado, voc j sabe que isso no funciona. A razo que esse bloco de script serapenas avaliado, e avali-lo (com eval() ) no criar uma funo chamada faleAlgo . Nada de tilacontecer com esse script. Para criar essa funo ns precisamos mudar nosso script para que ele crie defato a funo. Veja o exemplo corrigido.

  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    8/25

    faleAlgo = function(){alert('Ol');

    };

    Perceba que no exemplo acima ns no empregamos a palavra-chave var para declarar a varivel (funo).Se fizssemos isso a varivel/funo seria criada mas ficaria de acesso restrito ao escopo do prprio bloco descript (pelo menos no IE). Sem usar var a funo ser criada no escopo global, que nosso objetivo.Para mais detalhes sobre essa classe, veja e referncia do Ajax.Updater e a referncia das opes .

    Enumerando... Uau! Putz! Oba!Ns estamos acostumados com os laos do tipo for. Do tipo, crie seu array, preencha-o com elementos domesmo tipo, crie uma estrutura de lao (for, foreach, while, repeat, etc), acesse cada elemento na seqncia,usando seu ndice numrico, e faa algo til com o elemento.Se voc parar pra pensar, quase todas as vezes que voc usa um array em seu cdigo significa que vocestar utilizando aquele array em algum lao dentro em breve. No seria legal se os objetod do tipo array

    tivessem mais suporte para trabalhar com esses tipos de iteraes? Sim, seria, e muitas linguagens deprogramao possuem funcionalidade desse tipo em seus arrays ou estruturas equivalentes (tais comocolees, filas e listas).Bem, acontece que a prototype.js nos d o objeto Enumerable que implementa uma enormidade de truquespara usarmos quando trabalhando com dados iterveis. A biblioteca vai alm e extende a classe Array comtodos os mtodos de Enumerable .

    sumrio

    Laos a la RubyEm javascript padro, se voc quiser mostrar sequencialmente os elementos de um array, voc podetranqilamente escrever algo assim.

    function mostraLisat(){

    var simpsons = ['Homer', 'Marge', 'Lisa', 'Bart', 'Meg'];for(i=0;i

  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    9/25

    Tal como mencionamos acima, muito comum que todos os elementos de seu array sejam de um mesmotipo, com as mesmas propriedades e mtodos. Vejamos como podemos tirar proveito de funes iteradorascom nossos novos arrays envenenados.Encontrando um elemento de acordo com um critrio de busca.

    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

    }

    Buchanan, StevenCallahan, LauraDavolio, Nancy

    Agora vamos ao prximo passo. Vamos ver como podemos filtrar items dos arrays e depois retornar apenasum membro de cada elemento.

    function mostreLinksLocais(paragrafo){

    paragrafo = $(paragrafo);var links = $A(paragrafo.getElementsByTagName('a'));//vamos achar os links que tm rel="local"var linksLocais = links.findAll( function(link){

    var rel = link.getAttribute("rel");return rel =='local';

    });//agora vamos extrair o texto de cada linkvar textos = linksLocais.pluck('innerHTML');//vamos colocar os textos em uma nica stringvar resultado = textos.inspect();alert(resultado);

    }

    Este texto temvrioslinks. Alguns soexternose alguns so locais

    S preciso um pouco de prtica para ficar completamente viciado nessa sintaxe. D uma olhada nasreferncias de Enumerable e Array para ver uma lista de todas as funes disponveis.

    sumrio

    Livros que eu recomendo

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Enumerable%23Reference.Enumerablehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Array%23Reference.Arrayhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Enumerable%23Reference.Enumerablehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Reference.Array%23Reference.Arrayhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23toc
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    10/25

    H livros que so to bons que no d pra deixar de recomendar. Os livros abaixo me ajudaramenormemente a aprender as novas tcnicas necessrias para se construir uma aplicao AJAX e tambmconsolidaram as tcnicas que eu achava que j dominava. Eu acredito que um bom livro um dinheiro bemgasto. um investimento que se paga e continua a se pagar por um bom tempo.

    sumrio

    Referncia da prototype.js

    Extenses das classes JavaScriptUma das formas que prototype.js adiciona funcionalidade extendendo as classes JavaScript existentes.

    sumrio

    Extenses da classe Object

    Mtodo Tipo Argumentos Descrio

    extend(destination,source) esttico

    destination: qualquerobjeto, source:qualquer objeto

    Provm uma forma de se conseguir herana aose copiar todas as propriedades e mtodos de

    source para destination .

    inspect(targetObj) esttico targetObj: qualquerobjeto

    Retorna uma string legvel que representatargetObj. Caso o objeto passado no

    implemente um mtodo inspect ento afuno retornar toString .

    sumrio

    Extenses da classe NumberMtodo Tipo Argumentos Descrio

    toColorPart() deobjeto (nenhum)Retorna a representao hexadecimal do nmero.

    til quando se quer converter valores RGB deuma cor para seu formato em HTML.

    succ() deobjeto (nenhum)Retorna o prximo nmero. Esse mtodo

    comumente utilizado em contextos que envolvemiteraes.

    times(iterator) deobjeto

    iterator: uma funo comassinatura equivalente aFunction(valor, indice)

    Executa a funo iterator repetidamente,

    passando os parmetros valor e indicecontendo o valor da vez na iterao e o ndice davez, respectivamente.

    O exemplo a seguir mostrar mensagens com os nmeros de 0 a 9.

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.amazon.com/dp/0974514055?tag=sergiopereira-20&link_code=as3&creativeASIN=0974514055&creative=373489&camp=211189http://www.amazon.com/dp/0201760401?tag=sergiopereira-20&link_code=as3&creativeASIN=0201760401&creative=373489&camp=211189http://www.amazon.com/dp/0735712018?tag=sergiopereira-20&link_code=as3&creativeASIN=0735712018&creative=373489&camp=211189http://www.amazon.com/dp/1932394613?tag=sergiopereira-20&link_code=as3&creativeASIN=1932394613&creative=373489&camp=211189http://www.amazon.com/dp/0764579088?tag=sergiopereira-20&link_code=as3&creativeASIN=0764579088&creative=373489&camp=211189http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23toc
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    11/25

    function usandoTimes(){var n = 10;n.times(function(valor, indice){

    alert(indice);});/***************************

    * Tambem daria certo assim:* (10).times( .... );***************************/

    }

    sumrio

    Extenses da classe Function

    Mtodo Tipo Argumentos Descrio

    bind(object) deobjeto

    object: o objeto aoqual o mtodo

    pertence

    Retorna uma instncia da funo atrelada aoobjeto que contm. A nova funo tm os

    mesmos argumentos que a original.

    bindAsEventListener(object) deobjeto

    object: o objeto aoqual o mtodo

    pertence

    Retorna uma instncia da funo atrelada aoobjeto que contm. A nova funo ter o

    objeto event atual como argumento.

    Vamos ver como se usam essas extenses.

    Test?

    //declarando a classevar CheckboxWatcher = Class.create();

    //definindo o resto da classeCheckboxWatcher.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');

    sumrio

    Extenses da classe String

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23toc
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    12/25

    Mtodo Tipo Argumentos Descrio

    stripTags() deobjeto (nenhum) Retorna a string subtraindo quaisquer tags HTML ou XML.

    stripScripts() deobjeto (nenhum) Retorna a string, subtraindo quaisquer blocos .

    escapeHTML() deobjeto (nenhum)Retorna a string dando escape em quaisquer caracteres de

    marcao HTML.

    unescapeHTML() deobjeto (nenhum) A operao reversa de escapeHTML()

    extractScripts() deobjeto (nenhum)Retorna um objeto Array com mtodos os blocos

    encontrados na string.

    evalScripts() deobjeto (nenhum) Avalia todos os blocos encontrados na string.

    toQueryParams() deobjeto (nenhum)Separa a string em um array associativo indexado pelo nome de

    cada parametro (tal como um hash).

    parseQuery() deobjeto (nenhum) Mesmo que toQueryParams() .

    toArray() deobjeto (nenhum) Retrorna um Array com cada caractere da string.

    camelize() deobjeto (nenhum)Converte um string-separada-por-hfens em uma

    stringFormatadaComCamelCase. Essa funo pode ser til quandose lida com propriedades de estilo, por exemplo.

    sumrio

    Extenses da classe ArrayDe cara, a classe Array extende Enumerable , ento todos aqueles mtodos teis de Enumerable estodisponveis. Alem destes, os mtodos a seguir tambm esto includos.

    Mtodo Tipo Argumentos Descrio

    clear() deobjeto (nenhum) Esvazia o array e retorna-o.

    first() deobjeto (nenhum) Retorna o primeiro elemento do array.

    last() deobjeto (nenhum) Retorna o ltimo elemento do array.

    compact() deobjeto (nenhum)

    Retorna o array sem os elementos que

    sejam null ou undefined . Estemtodo no altera o array original,apenas retorna um novo.

    flatten() deobjeto (nenhum)

    Retorna uma verso unidimensional(achatada) do array. Esse achatamentoocorre porque cada elemento do array

    que tambm um array ter seuselementos includos no array-pai. Esse

    processo ocorre de forma recursiva paracada elemento.

    without(valor1 [, valor2 [,.. valorN]])

    deobjeto

    valor1 ... valorN:valores a serem

    excludos seencontrados no array.

    Retorna o array subtraindo os elementoslistados como argumentos.

    indexOf(valor) deobjetovalor: o valor

    procurado.

    Retorna o ndice, baseado em zero, doprimeiro elemento encontrado com o valor . Retorna -1 se nenhuma

    ocorrncia for encontrada.

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23toc
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    13/25

    reverse([alterarOriginal]) deobjeto

    alterarOriginal:indica se o array

    original serrevertido.

    Retorna o array em ordem reversa. Senenhum argumento for dado ou se oargumento for true ento o array

    original tambm ser revertido. Casocontrrio ele permanecer do jeito que

    est.

    shift() deobjeto (nenhum)Retorna o primeiro elemento do array eretira-o do array, reduzindo o tamanho

    do array em 1 elemento.

    inspect() deobjeto (nenhum)Retorna uma string com os elementos do

    array.sumrio

    Extenses do objeto document do DOM

    Mtodo Tipo Argumentos Descrio

    getElementsByClassName(nomeDaClasse

    [, elementoPai])

    de

    objeto

    nomeDaClasse: nome daclase CSS associada com os

    elementos, elementoPai:

    objeto ou id do elementoque contm os elementos aserem buscados.

    Retorna todos oselementos com a classe

    CSS informada. Se oelemento-pai no for

    dado, ento os elementossero procurados dentro

    do elemento body .sumrio

    Extenses do objeto Event

    Propriedade Tipo Descrio

    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.

    Mtodo Tipo Argumentos Descrio

    element(event) esttico event: an Event object Returns element thatoriginated the event.

    isLeftClick(event) esttico event: an Event objectReturns true if the left

    mouse button was clicked.

    pointerX(event) esttico event: an Event object Returns the x coordinate of the mouse pointer on thepage.

    pointerY(event) esttico event: an Event objectReturns the y coordinate of the mouse pointer on the

    page.

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23toc
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    14/25

    stop(event) esttico event: an Event object

    Use this function to abortthe default behavior of anevent and to suspend its

    propagation.

    findElement(event, tagName) esttico event: an Event object, tagName:name of the desired tag.

    Traverses the DOM treeupwards, searching for thefirst element with the given

    tag name, starting fromthe element that originated

    the event.

    observe(element, name,observer, useCapture) esttico

    element: object or id, name:event name (like 'click',

    'load', etc), observer: functionto handle the event, useCapture:

    if true , handles the event inthe capture phase and if false

    in the bubbling phase.

    Adds an event handlerfunction to an event.

    stopObserving(element,name, observer, useCapture) esttico

    element: object or id, name:event name (like 'click'),observer: function that is

    handling the event, useCapture:

    if true handles the event in thecapture phase and if false in

    the bubbling phase.

    Removes an event handlerfrom the event.

    _observeAndCache(element,name, observer, useCapture) esttico

    Private method, do notworry about it.

    unloadCache() esttico (nenhum)

    Private method, do notworry about it. Clears allcached observers from

    memory.

    Let's see how to use this object to add an event handler to the load event of the window object.

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

    function showMessage() {alert('Page loaded.');

    }

    sumrio

    Novos objetos e classes definidos em prototype.jsOutra forma que a biblioteca ajuda ao disponibilizar diversos objetos que implementam suporte a designorientado a objetos e tambm funcionalidades de uso geral.

    sumrio

    The PeriodicalExecuter objectThis object provides the logic for calling a given function repeatedly, at a given interval.

    Mtodo Tipo Argumentos Descrio

    [ctor](callback,interval) constructor

    callback: a parameterlessfunction, interval: number of

    seconds

    Creates one instance of this objectthat will call the function

    repeatedly.

    Propriedade Tipo Descrio

    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

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23toc
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    15/25

    sumrio

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

    Propriedade Tipo Descrio

    Version String The version of the library

    emptyFunction Function() An empty function object sumrio

    The Class objectThe Class object is used when declaring the other classes in the library. Using this object when declaring aclass causes the to new class to support an initialize() method, which serves as the constructor.See the sample below.

    //declaring the classvar MySampleClass = Class.create();

    //defining the rest of the class implmentationMySampleClass.prototype = {

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

    },

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

    }};

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

    Mtodo Tipo Argumentos Descrio

    create(*) de objeto (any) Defines a constructor for a new class

    The Ajax objectThis object serves as the root for many other classes that provide AJAX functionality.

    Mtodo Tipo Argumentos DescriogetTransport() de objeto (nenhum) Returns a new XMLHttpRequest object

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

    Mtodo Tipo Argumentos Descrio

    setOptions(options) deobjetooptions: AJAX

    options Sets the desired options for the AJAX operation

    responseIsSuccess() deobjeto (nenhum) Returns true if the AJAX operation succeeded, falseotherwise

    responseIsFailure() deobjeto (nenhum) The opposite of responseIsSuccess() .

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.optionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.optionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.optionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#toc%23tochttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.optionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.optionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.options
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    16/25

    The Ajax.RequestInherits from Ajax.BaseEncapsulates AJAX operations

    Propriedade Tipo Tipo Descrio

    Events Array estticoList of possible events/statuses reported during an AJAX operation.The list contains: 'Uninitialized', 'Loading', 'Loaded', 'Interactive',

    and 'Complete.'

    transport XMLHttpRequest deobjeto The XMLHttpRequest object that carries the AJAX operation

    Mtodo Tipo Argumentos Descrio

    [ctor](url, options) constructor

    url: the url tobe fetched,

    options: AJAXoptions

    Creates one instance of this object thatwill call the given url using the given

    options . Important: It is worth notingthat the chosen url is subject to theborwser's security settings. In many

    cases the browser will not fetch the url if it is not from the same host (domain) asthe current page. You should ideally use

    only local urls to avoid having toconfigure or restrict the user's browser.

    (Thanks Clay).

    request(url) de objeto url: url forthe AJAX call

    This method is typically not called

    externally. It is already called during theconstructor call.

    setRequestHeaders() de objeto (nenhum)

    This method is typically not calledexternally. 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 (1to 4)

    This method is typically not calledexternally. It is called by the object itself

    when the AJAX call status changes.

    The options argument objectAn important part of the AJAX operations is the options argument. There's no options class per se. Anyobject 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 Descrio

    method String 'post' Method of the HTTP request

    parameters String '' The url-formatted list of values passed to therequest

    asynchronous Boolean true Indicates if the AJAX call will be madeasynchronously

    postBody String undefined Content passed to in the request's body in case of a HTTP POST

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Base%23Ajax.Basehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Base%23Ajax.Base
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    17/25

    requestHeaders Array undefined

    List of HTTP headers to be passed with therequest. This list must have an even number of

    items, any odd item is the name of a customheader, 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 respectiveevent/status is reached during the AJAX call.

    Example var myOpts = {onComplete:showResponse, onLoaded:registerLoaded}; . The function used will

    receive one argument, containing theXMLHttpRequest object that is carrying the

    AJAX operation.

    onSuccess Function(XMLHttpRequest) undefined

    Custom function to be called when the AJAX callcompletes successfully. The function used will

    receive one argument, containing theXMLHttpRequest object that is carrying the

    AJAX operation.

    onFailure Function(XMLHttpRequest) undefined

    Custom function to be called when the AJAX callcompletes with error. The function used will

    receive one argument, containing theXMLHttpRequest object that is carrying the

    AJAX operation.

    insertion Function(Object, String) null

    Function to be called to inject the returned textinto an element. The function will be called with

    two arguments, the element object to be updatedand the response text Applies only to

    Ajax.Updater objects.

    evalScripts Boolean undefined,false

    Determines if script blocks will be evaluated whenthe 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 thelast 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 muchtime for the next refresh. If it repeats again, theobject will wait four times as much, and so on.

    Leave it undefined or use 1 to avoid the slowdown.

    The Ajax.UpdaterInherits from Ajax.RequestUsed 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 blocks that will be evaluated upon arrival. Usethe evalScripts option to work with scripts.

    Propriedade Tipo Tipo Descrio

    ScriptFragment String esttico A regular expression to identify scripts

    containers Object deobjeto

    This object contains two properties:containers.success

    will be usedwhen the AJAX call succeeds, and containers.failure will be used

    otherwise.

    Mtodo Tipo Argumentos Descrio

    [ctor](container,url, options)

    constructor container:this can be the id ofan element, the element object

    Creates one instance of this object

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Updater%23Ajax.Updaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Updater%23Ajax.Updaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.PeriodicalUpdater%23Ajax.PeriodicalUpdaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Request%23Ajax.Requesthttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Updater%23Ajax.Updaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Updater%23Ajax.Updaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.PeriodicalUpdater%23Ajax.PeriodicalUpdaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Request%23Ajax.Request
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    18/25

    itself, or an object with twoproperties - object.success

    element (or id) that will be usedwhen the AJAX call succeeds, and

    object.failure element (or id)that will be used otherwise. url:

    the url to be fetched, options: AJAX options

    that will call the given url usingthe given options .

    updateContent() de objeto (nenhum)

    This method is typically not calledexternally. It is called by the

    object itself when the response isreceived. It will update the

    appropriate element with the HTML or call the function passed in theinsertion option. The functionwill be called with two arguments,the element to be updated and the

    response text.

    The Ajax.PeriodicalUpdaterInherits from Ajax.Base

    This class repeatedly instantiates and uses an Ajax.Updater object to refresh an element on the page, orto perform any of the other tasks the Ajax.Updater can perform. Check the Ajax.Updater reference formore information.

    Propriedade Tipo Tipo Descrio

    container Object deobjeto This value will be passed straight to the Ajax.Updater 's constructor.

    url String deobjeto This value will be passed straight to the Ajax.Updater 's constructor.

    frequency Numberde

    objeto

    Interval (not frequency) between refreshes, in seconds. Defaults to 2

    seconds. This number will be multiplied by the current decay wheninvoking the Ajax.Updater object

    decay Number deobjeto Keeps the current decay level applied when re-executing the task

    updater Ajax.Updater deobjeto The most recently used Ajax.Updater object

    timer Object deobjetoThe JavaScript timer being used to notify the object when it is time for

    the next refresh.

    Mtodo Tipo Argumentos Descrio

    [ctor](container,url, options) constructor

    container:this can be the id of anelement, the element object itself,or an object with two properties -

    object.success element (or id) thatwill be used when the AJAX callsucceeds, and object.failure

    element (or id) that will be usedotherwise. url: the url to be

    fetched, options: AJAX options

    Creates one instance of thisobject that will call the given

    url using the givenoptions .

    start() de objeto (nenhum)

    This method is typically notcalled externally. It is calledby the object itself to start

    performing its periodicaltasks.

    stop() de objeto (nenhum) This method is typically notcalled externally. It is calledby the object itself to stopperforming its periodical

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.optionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Base%23Ajax.Basehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Updater%23Ajax.Updaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Updater%23Ajax.Updaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.optionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.optionshttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Base%23Ajax.Basehttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Updater%23Ajax.Updaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.Updater%23Ajax.Updaterhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Ajax.options%23Ajax.options
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    19/25

    tasks.

    updateComplete() de objeto (nenhum)

    This method is typically notcalled externally. It is called

    by the currently used Ajax.Updater after if completes the request. It isused to schedule the next

    refresh.

    onTimerEvent() de objeto (nenhum)This method is typically notcalled externally. It is calledinternally when it is time for

    the next update.

    The Element objectThis object provides some utility functions for manipulating elements in the DOM.

    Mtodo Tipo Argumentos Descrio

    toggle(elem1 [, elem2 [,elem3 [...]]])

    deobjeto

    elemN: element object orid

    Toggles the visibility of each passedelement.

    hide(elem1 [, elem2 [, elem3[...]]])

    deobjeto

    elemN: element object orid

    Hides each element bu setting itsstyle.display to 'none' .

    show(elem1 [, elem2 [, elem3[...]]])

    deobjeto

    elemN: element object orid

    Shows each element bu resetting itsstyle.display to '' .

    remove(element) deobjetoelement: element object

    or idRemoves the element from the

    document.

    getHeight(element) deobjetoelement: element object

    or idReturns the offsetHeight of the

    element

    addClassName(element,className)

    deobjeto

    element: element objector id, className: name ofa CSS class

    Adds the given class name to theelement's class names.

    hasClassName(element,className)

    deobjeto

    element: element objector id, className: name of

    a CSS class

    Returns true if the element has thegiven class name as one of its class

    names.

    removeClassName(element,className)

    deobjeto

    element: element objector id, className: name of

    a CSS class

    Removes the given class name fromthe element's class names.

    cleanWhitespace(element) deobjetoelement: element object

    or idRemoves any white space text node

    children of the element

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

    The Abstract.InsertionThis class is used as the base class for the other classes that will provide dynamic content insertion. This classis used like an abstract class.

    Mtodo Tipo Argumentos Descrio

    [ctor](element,content) constructor

    element: element object or id,content: HTML to be inserted

    Creates an object that will helpwith dynamic content insertion.

    Propriedade Tipo Tipo Descrio

    adjacency String static,parameter

    Parameter that specifies where the content will be placed relative to the

  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    20/25

    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 objectThis 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.BeforeInherits from Abstract.Insertion Inserts HTML before an element.

    Mtodo Tipo Argumentos Descrio

    [ctor](element,content) constructor

    element: element objector id, content: HTML to

    be inserted

    Inherited from Abstract.Insertion .Creates an object that will help with dynamic

    content insertion.

    The following code
    Hello, Wiggum. How's it going?

    new Insertion.Before('person', 'Chief ');

    Will change the HTML to


    Hello, Chief Wiggum. How's it going?

    The Insertion.TopInherits from Abstract.Insertion Inserts HTML as the first child under an element. The content will be right after the opening tag of theelement.

    Mtodo Tipo Argumentos Descrio

    [ctor](element,content) constructor

    element: element objector id, content: HTML to

    be inserted

    Inherited from Abstract.Insertion .Creates an object that will help with dynamic

    content insertion.

    The following code


    Hello, Wiggum. How's it going? new Insertion.Top('person', 'Mr. ');

    Will change the HTML to


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

    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.Mtodo Tipo Argumentos Descrio

    [ctor](element,content) constructor

    element: element objector id, content: HTML to

    be inserted

    Inherited from Abstract.Insertion .Creates an object that will help with dynamic

    content insertion.

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertion
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    21/25

    The following code


    Hello, Wiggum. How's it going?

    new Insertion.Bottom('person', " What's up?");

    Will change the HTML to


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

    The Insertion.AfterInherits from Abstract.Insertion Inserts HTML right after the element's closing tag.

    Mtodo Tipo Argumentos Descrio

    [ctor](element,content) constructor

    element: element objector id, content: HTML to

    be inserted

    Inherited from Abstract.Insertion .Creates an object that will help with dynamic

    content insertion.

    The following code


    Hello, Wiggum. How's it going?

    new Insertion.After('person', ' Are you there?');

    Will change the HTML to


    Hello, Wiggum. How's it going? Are youthere?

    The Field object

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

    Mtodo Tipo Argumentos Descrio

    clear(field1 [, field2 [,field3 [...]]])

    deobjeto

    fieldN: field elementobject or id

    Clears the value of each passed formfield element.

    present(field1 [, field2 [,field3 [...]]])

    deobjeto

    fieldN: field elementobject or id

    Returns true only if all forms fieldscontain non-empty values.

    focus(field) deobjetofield: field element

    object or idMoves the input focus to the given form

    field.

    select(field) deobjetofield: field element

    object or id Selects the value in fields that supporttext selection

    activate(field) deobjetofield: field element

    object or idMove the focus and selects the value in

    fields that support text selection

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

    Mtodo Tipo Argumentos Descrio

    serialize(form) deobjeto

    form: formelement

    object or id

    Returns a url-formatted list of field names and their values,like

    'field1=value1&field2=value2&field3=value3'

    getElements(form) deobjeto

    form: formelement

    object or idReturns an Array containing all the input fields in the form.

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertionhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.Insertion%23Abstract.Insertion
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    22/25

    getInputs(form [,typeName [, name]])

    deobjeto

    form: formelement

    object orid,

    typeName:the type of

    the inputelement,

    name: thename of the

    input

    element.

    Returns an Array containing all the elements inthe form. Optionally, the list can be filtered by the type or

    name attributes of the elements.

    disable(form) deobjeto

    form: formelement

    object or idDisables all the input fields in the form.

    enable(form) deobjeto

    form: formelement

    object or idEnables all the input fields in the form.

    focusFirstElement(form) deobjeto

    form: formelement

    object or idActivates the first visible, enabled input field in the form.

    reset(form) deobjetoform: formelement

    object or idResets the form. The same as calling the reset() method

    of the form object.

    The Form.Element objectThis object provides some utility functions for working with form elements, visible or not.

    Mtodo Tipo Argumentos Descrio

    serialize(element) deobjetoelement: element

    object or idReturns the element's name=value pair, like

    'elementName=elementValue'

    getValue(element) deobjetoelement: element

    object or id Returns the value of the element.

    The Form.Element.Serializers objectThis object provides some utility functions that are used internally in the library to assist extracting thecurrent value of the form elements.

    Mtodo Tipo Argumentos Descrio

    inputSelector(element) deobjeto

    element: object or id of aform element that has thechecked property, like a

    radio button or checkbox.

    Returns an Array with the element'sname and value, like ['elementName',

    'elementValue']

    textarea(element) deobjeto

    element: object or id of aform element that has the

    value property, like atextbox, button or password

    field.

    Returns an Array with the element'sname and value, like ['elementName',

    'elementValue']

    select(element) deobjetoelement: object or id of a

    element

    Returns an Array with the element'sname and all selected options' values or

    texts, like ['elementName','selOpt1 selOpt4 selOpt9']

    The Abstract.TimedObserverThis class is used as the base class for the other classes that will monitor one element until its value (orwhatever 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.

  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    23/25

    Mtodo Tipo Argumentos Descrio

    [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 willmonitor the element.

    getValue() instance,abstract (nenhum)

    Derived classes have toimplement this method to

    determine what is the currentvalue being monitored in the

    element.

    registerCallback() de objeto (nenhum)

    This method is typically notcalled externally. It is called by

    the object itself to startmonitoring the element.

    onTimerEvent() de objeto (nenhum)

    This method is typically notcalled externally. It is called bythe object itself periodically to

    check the element.

    Propriedade Tipo Descrio

    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.ObserverInherits from Abstract.TimedObserver Implementation of an Abstract.TimedObserver that monitors the value of form input elements. Use thisclass when you want to monitor an element that does not expose an event that reports the value changes. Inthat case you can use the Form.Element.EventObserver class instead.

    Mtodo Tipo Argumentos Descrio

    [ctor](element,frequency,callback)

    constructor

    element: element object orid, 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.ObserverInherits from Abstract.TimedObserver Implementation of an Abstract.TimedObserver that monitors any changes to any data entry element'svalue in a form. Use this class when you want to monitor a form that contais a elements that do not exposean event that reports the value changes. In that case you can use the Form.EventObserver class instead.

    Mtodo Tipo Argumentos Descrio

    [ctor](form,frequency,callback)

    constructor

    form: form object or id,frequency: interval in

    seconds, callback: functionto be called when any dataentry element in the form

    changes

    Inherited from Abstract.TimedObserver . Creates an

    object that will monitor the form forchanges.

    getValue() de objeto (nenhum) Returns the serialization of all form's data.

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.TimedObserver%23Abstract.TimedObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.EventObserver%23Form.Element.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.TimedObserver%23Abstract.TimedObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.TimedObserver%23Abstract.TimedObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.EventObserver%23Form.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.TimedObserver%23Abstract.TimedObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.TimedObserver%23Abstract.TimedObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.EventObserver%23Form.Element.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.TimedObserver%23Abstract.TimedObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.TimedObserver%23Abstract.TimedObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.EventObserver%23Form.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.TimedObserver%23Abstract.TimedObserver
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    24/25

    The Abstract.EventObserverThis 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 wipingout 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 generaland listboxes/dropdowns.

    Mtodo Tipo Argumentos Descrio

    [ctor](element,callback) constructor

    element: element objector id, callback: function

    to be called when theevent happens

    Creates an object that will monitorthe element.

    getValue() instance,abstract (nenhum)

    Derived classes have to implementthis method to determine what isthe current value being monitored

    in the element.

    registerCallback() de objeto (nenhum)

    This method is typically not calledexternally. It is called by the object

    to bind itself to the element'sevent.

    registerFormCallbacks() de objeto (nenhum)

    This method is typically not calledexternally. It is called by the objectto bind itself to the events of eachdata entry element in the form.

    onElementEvent() de objeto (nenhum)This method is typically not calledexternally. It will be bound to the

    element's event.

    Propriedade Tipo Descrio

    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.EventObserverInherits from Abstract.EventObserver Implementation of an Abstract.EventObserver that executes a callback function to the appropriateevent of the form data entry element to detect value changes in the element. If the element does not exposeany event that reports changes, then you can use the

    Form.Element.Observerclass instead.

    Mtodo Tipo Argumentos Descrio

    [ctor](element,callback) constructor

    element: element objector id, callback:

    function to be calledwhen 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 elementcontained in a form, using the elements' events to detect when the value changes. If the form containselements that do not expose any event that reports changes, then you can use the Form.Observer classinstead.

    Mtodo Tipo Argumentos Descrio

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.EventObserver%23Abstract.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.Observer%23Form.Element.Observerhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.EventObserver%23Abstract.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.EventObserver%23Abstract.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Observer%23Form.Observerhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.EventObserver%23Abstract.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Element.Observer%23Form.Element.Observerhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.EventObserver%23Abstract.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.EventObserver%23Abstract.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Form.Observer%23Form.Observer
  • 8/8/2019 Anotaes de um desenvolvedor sobre a prototype

    25/25

    [ctor](form,callback) constructor

    form: form object or id,callback: function to be

    called when any data entryelement in the form changes

    Inherited from Abstract.EventObserver . Creates anobject 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.

    Mtodo Tipo Argumentos Descrio

    prepare() deobjeto (nenhum)

    Adjusts the deltaX and deltaYproperties to accomodate changes in the

    scroll position. Remember to call thismethod before any calls to

    withinIncludingScrolloffsetafter the page scrolls.

    realOffset(element) de

    objeto

    element:

    object

    Returns an Array with the correct scrolloffsets 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) deobjetoelement:

    object

    Returns an Array with the correctpositioning offsets of the element,

    including any offsets that are imposed bypositioned parent elements. The

    resulting array is similar to[total_offset_left,

    total_offset_top]

    within(element, x, y) deobjeto

    element:object, x and

    y: coordinatesof a point

    Tests if the given point coordinates areinside the bounding rectangle of the

    given element

    withinIncludingScrolloffsets(element,x, y)

    deobjeto

    element:object, x and

    y: coordinatesof a point

    overlap(mode, element) deobjeto

    mode:'vertical' or'horizontal',

    element:object

    within() needs to be called rightbefore calling this method. This methodwill return a decimal number between

    0.0 and 1.0 representing the fraction of

    the coordinate that overlaps on theelement. As an example, if the elementis a square DIV with a 100px side and

    positioned at (300, 300), thenwithin(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 objector id

    Resizes and repositions the target

    element identically to the sourceelement.

    http://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.EventObserver%23Abstract.EventObserverhttp://www.sergiopereira.com/articles/prototype140.js.ptBR.html#Abstract.EventObserver%23Abstract.EventObserver