Prototype Makes Javascript Painless

prototype.gifPrototype is an excellent tool but lacking in documentation, causing me to fumble around and *gasp* look at the source code. As any developer knows, when reviewing code there is a chance that you may miss something or ignore what doesn't seem interesting. In doing so, you may miss some sweet features that you would otherwise use.

I did stumble upon some Prototype Cheat Sheets that have helped immensely in exposing functions that existed in Prototype that I had no clue were there. Desipte the exposure of function names, I was at a loss for what some of them did. Luckily, there is an article over at SergioPeriera.com that documents many of those functions! The documentation is fairly solid so I HIGHLY reccommend checking it out. Here's one of the features of Prototype that I had seen the function but hadn't a firm understanding on what it did:

Try.these()
Tries a number of functions in order. If the first fails, it attempts the second, and so on.

JavaScript:
  1. function getXmlNodeValue(xmlNode){
  2.     return Try.these(
  3.         function() {return xmlNode.text;},
  4.         function() {return xmlNode.textContent;)
  5.         );
  6. }

Hugely cool. In addition, Ajaxian - which seems to be my source for many things Ajax - has pointed me towards this article over at SitePoint. I was aware of a number of the points mentioned in that SitePoint article, but a few stood out as super sexy. Here's the juicy tidbits:

String.times([something])
Prototype adds a great method to Number, too. Say goodbye to your for loops!

JavaScript:
  1. // alerts "1", "2", "3" ... "50"
  2. (50).times(function(n) { alert(n); });

Enumberable.each([something])
This does the same as a foreach in PHP. I've been looking for something like this!

JavaScript:
  1. // alerts "a is at 0" then "b is at 1" then "c is at 2"
  2. ["a", "b", "c"].each(function(item, index) {
  3.  alert(item + " is at " + index);
  4. });

Iterating over childNodes in the DOM
By default, even though nodes are represented in Array-like form, they do not have Enumerable available to them automatically. Here's how to do it:

JavaScript:
  1. // add Enumerable to childNodes
  2. var children = $A($("mydiv").childNodes);
  3.  
  4. // sets class="highlighted" for all child nodes of "mydiv"
  5. children.each(function(child) {
  6.  child.setAttribute("class", "highlighted");
  7. });

Here's one I found while digging around in the Prototype code that the article solidified my understanding:

Ajax.PeriodicalUpdater(id,file,options)
Periodically does an Ajax.Updater call!

JavaScript:
  1. new Ajax.PeriodicalUpdater("mydiv", "hello.php", {
  2.  // initial number of seconds interval between calls
  3.  frequency : 1,
  4.  decay : 2
  5. });

The decay option allows you to give your server a bit of a break if it's returning a lot of identical responses. Essentially, every time PeriodicalUpdater makes a request, it compares the results with what the server returned last time. If the values are the same, it multiplies the interval by the decay value. So, for the above example, it would make the next request two seconds later, then four seconds later, and so on, until it received a different result from the server. At that point, the interval would be reset to one second.

Ajax.Responders.register(options)
Register global event handlers that are triggered for each and every AJAX request that happens on the page.

JavaScript:
  1. Ajax.Responders.register({
  2.  onCreate : showLoader,
  3.  onComplete : hideLoader
  4. });

Discuss This Article


15 Responses to “Prototype Makes Javascript Painless”

  1. pingback pingback:
    BorkWeb » Blog Archive » Ajax; Templating; and the Separation of Layout and Logic

    [...] I have often mentioned my process of expanding my proficiency of Ajax. Through my journey I have made a number of wrong turns and hit my share of stumbling blocks. All of that has been a learning experience and I’m learning still. I began fiddling with XMLHttpRequest as many do - blissfully ignorant of the many frameworks that exist to make Ajax super easy. My code was bloated with some neat…’features’ (pronounced: bugs). [...]

    Reply to this comment.
    1
  2. pingback pingback:
    Ajaxian » Ajax Templating - Seperation of Layout and Logic

    [...] His solution? He uses the Behaviour libray that’s built on top of everyone’s favorite Javascript library, Prototype. With a few quick lines of Javascipt, a bulleted list is created so that, onClick the item selected will be removed from the list. [...]

    Reply to this comment.
    2
  3. pingback pingback:
    BorkWeb » Oooo event:Selectors for Prototype

    [...] Behaviour is a stand-alone event framework. You can use it regardless of whether or not you are using Prototype (or some other Ajax/Javascript library) - which is pretty cool. But…if you are using Prototype there is a lot of code duplication between the two libraries. Luckily, Mir.aculo.us has brought event:Selectors to my attention which is causing me to sing a different tune! Justin Palmer, event:Selector’s creator is crediting Behaviour for the idea, but he’s has what Behaviour has done a few steps further. [...]

    Reply to this comment.
    3
  4. pingback pingback:
    BorkWeb » A Simple Server-Side Ajax Handler

    [...] As I have stated in the past, I’m a huge fan of Prototype AND I choose PHP as my language of choice…so my examples will be using both, but the idea can be used anywhere. [...]

    Reply to this comment.
    4
  5. pingback pingback:
    BorkWeb » Practicing What I Preach

    [...] MasterWish was built using SAJAX as the tool of choice for Ajax communication but as I’ve mentioned in the past, I am a Prototype convert. My knowledge of Ajax, JSON, and general application structure has been morphing so much in recent weeks that I have held off in completely revamping the wish list site. [...]

    Reply to this comment.
    5
  6. pingback pingback:
    BorkWeb » Script.aculo.us v1.6 Soon

    [...] Great news over at Mir.aculo.us. It appears as if version 1.6 of my favorite DOM manipulation library, Script.aculo.us will be out soon. Thankfully the new version of Script.aculo.us will be using Prototype v1.5. [...]

    Reply to this comment.
    6
  7. pingback pingback:
    BorkWeb » Speeding Up Prototype’s $$ Selector

    [...] Prototype, as I’ve stated in the past, is our Javascript library of choice for Ajax at Plymouth State University and in the current re-writing of MasterWish. As of version 1.5 of Prototype there has been a sweet Selector function $$ which is best used when manipulating more than one dom element of the same type…i.e. updating all buddies in a buddy list at MasterWish with some property. [...]

    Reply to this comment.
    7
  8. pingback pingback:
    Prototype » STARTREK.COM : Episode

    [...] BorkWeb ” Prototype Makes Javascript Painless … Prototype is an excellent tool but lacking in documentation, causing me to fumble around and *gasp* look at … I did stumble upon some Prototype Cheat Sheets that have helped immensely … [...]

    Reply to this comment.
    8
  9. pingback pingback:
    BorkWeb » Prototype Changes

    [...] I found this article via Ajaxian regarding a nice block of Prototype updates. [...]

    Reply to this comment.
    9
  10. AvatarJames Laver

    I’m sorry but I’m failing to see how this isn’t just ruby ideas applied to javascript. Honestly, when frameworks like turbogears and django can eliminate most of the javascript tedium anyway, I don’t see much of a place for this.

    Reply to this comment.
    10
  11. AvatarJames Laver

    Oh, and xajax is pretty cool too, you write all your code in php and it generates the javascript. Much nicer imho.

    Reply to this comment.
    11
  12. AvatarError in source

    the example:
    50.times(function(n) { alert(n); });

    gives errors, it’s supposed to be
    (50).times(function(n) { alert(n); });

    Reply to this comment.
    12
  13. pingback pingback:
    BorkWeb » The Ajax Experience: jQuery Toolkit

    [...] I went to The Ajax Experience with high expectations of catching some great tips regarding development in an Ajax environment. At the same time, I was sure of my previous decision with the use of Prototype and Script.aculo.us was as good as it gets (without diving into the widgetized world…e.g. Dojo). I attended John Resig’s presentation on jQuery and I became a convert. [...]

    Reply to this comment.
    13
  14. Avatarxfwxeeljde

    Hello! Good Site! Thanks you! pdsudpanmo

    Reply to this comment.
    14
  15. Avatarcorey

    i believe in the Try.these example line 4 should end with a curly brace, not a parenthesis.

    Reply to this comment.
    15

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Comment Preview:

 (11029) - prototype examples (128) - Prototype samples (84) - prototype setattribute (79) - prototype onclick (33) - prototype childnodes (27) - prototype set attribute (25) - javascript prototype (25) - prototype example (24) - Ajax.PeriodicalUpdater example (21) - php prototype (17) - prototype PeriodicalUpdater (17) - prototype children (15) - javascript prototype foreach (15) - prototype (15) - periodicalupdater example (14) - setAttribute prototype (14) - javascript prototype onclick (13) - prototype javascript examples (13) - prototype childnode (11) - javascript foreach prototype (10) - prototype PeriodicalUpdater example (10) - prototype and php (9) - prototype child (9) - javascript getchild (9) - prototype add attribute (9) - javascript prototyping (8) - Ajax.Responders.register (8) - prototype javascript sample (7) - javascript prototype json (7) - javascript foreach childNodes (7) - Ajax.PeriodicalUpdater sample (6) - prototype onCreate (6) - javascript prototype samples (6) - ajax prototype examples (6) - javascript onclick prototype (5) - prototype child nodes (5) - javascript childnodes prototype (5) - javascript getchildelements (5) - prototype json php (4) - javascript iterate child nodes (4) - prototype php (4) - ajax.responders (4) - prototype javascript foreach (4) - prototype javascript samples (4) - javascript prototypes (4) - PeriodicalUpdater prototype (4) - prototype AJAX responders (4) - prototype ajax examples (4) - jscript prototype (4) - javascript prototype sample (4) - javascript prototype setattribute (4) - ajax PeriodicalUpdater example (4) - php prototype tutorial (4) - prototype convert string to number (3) - PeriodicalUpdater tutorial (3) - prototyping in javascript (3) - prototype PeriodicalUpdater tutorial (3) - javascript dom iterate child (3) - prototype get child nodes (3) - delay prototype javascript (3) - prototype addchild (3) - examples of prototype (3) - prototype foreach (3) - prototype set attributes (3) - jquery periodicalupdater (3) - best prototype examples (3) - prototype Ajax.PeriodicalUpdater example (3) - prototype javascript onclick (3) - prototype each examples (3) - example of prototype (3) - prototype getchild (3) - prototype onclick handler (2) - javascript iterate over all children (2) - javascript prototype tutorial (2) - prototype set onclick (2) - examples prototype (2) - prototype iterate over children (2) - prototype add child element (2) - javascript prototype xml node child (2) - prototype onclick javascript (2) - prototype with php (2) - prototype javascript convert number to string (2) - prototype""1.5""set attributes (2) - prototyping javascript (2) - prototype js onclick (2) - example PeriodicalUpdater (2) - javascript prototype Updater tutorial (2) - prototype iterating dom (2) - delay prototype example (2) - samples prototype (2) - prototype behaviour (2) - setAttributes javascript (2) - example of prototype php (2) - prototype ajax.updater json php (2) - prototype $$ examples (2) - prototypes setattribute (2) - child element javascript dom iterate (2) - js prototype onclick (2) - javascript prototype json processing each (2) - javascript iterate child node (2) - childNodes using prototype (2) - javascript prototype add child (2) - ajax morphing (2) - js prototype setAttribute (2) - Ajax.PeriodicalUpdater tutorial (2) - ajax examples prototype (2) - javascript iterate childnodes (2) - prototype convert string to integer (2) - ajax setattribute prototype (2) - foreach javascript prototype (2) - javascript prototype.onclick (2) - understanding prototype in javaScript (2) - PeriodicalUpdater examples (2) - onclick prototype (2) - prototype each (2) - javascript DOM getChild (2) - javascript xmlnode (2) - json php prototype (2) - prototype get child node (2) - Ajax.PeriodicalUpdater examples (2) - prototype AJAX.PeriodicalUpdater (2) - javascript childnodes foreach (2) - if Ajax.PeriodicalUpdater times out (1) - javascript prototype attribute (1) - onclick prototype function (1) - javascript foreach (1) - prototyping in javascript samples (1) - javascript interval decay (1) - onCreate prototype (1) - foreach javascript prototype how to (1) - setting a attribute in prototype (1) - Ajax.Updater PeriodicalUpdater requestHeaders (1) - best examples prototype (1) - prototype add onclick handler (1) - javascript prototype to integer (1) - file processing server side ajax periodicalupdater (1) - DOM getChildElements() (1) - javascript prototype $$( sample (1) - prototype .onClick (1) - ajax request examples prototype (1) - prototype children childnode (1) - prototype 1.6 tutorial (javascript) (1) - prototype in javascript (1) - prototype for each (1) - prototipe 2. (1) - js prototype child elements (1) - prototype exaple (1) - getChildren in java script (1) - json php update db prototype (1) -