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 (432) - Prototype samples (315) - prototype setattribute (292) - prototype onclick (132) - prototype set attribute (95) - php prototype (81) - prototype childnodes (77) - Ajax.PeriodicalUpdater example (76) - prototype javascript examples (72) - prototype children (63) - setAttribute prototype (58) - prototype PeriodicalUpdater (56) - javascript prototype (52) - prototype child (46) - prototype add attribute (43) - javascript foreach prototype (42) - Ajax.Responders.register (41) - prototype php (40) - javascript prototype foreach (37) - prototype add child (37) - javascript getchild (34) - prototype example (34) - periodicalupdater example (29) - prototype get child (29) - prototype addchild (29) - prototype (28) - prototype PeriodicalUpdater example (27) - javascript prototype example (27) - javascript prototype onclick (25) - javascript prototype examples (25) - javascript prototyping (25) - prototype onCreate (23) - prototype child nodes (23) - prototype and php (22) - ajax prototype examples (22) - prototype childnode (21) - prototype javascript sample (20) - javascript prototype json (20) - prototype javascript foreach (20) - prototype ajax examples (18) - samples prototype (18) - prototype add child element (18) - prototype getchild (18) - javascript foreach childNodes (16) - Ajax.PeriodicalUpdater sample (16) - onclick prototype (15) - prototype get children (15) - Ajax.PeriodicalUpdater examples (14) - javascript onclick prototype (14) - PeriodicalUpdater prototype (13) - javascript prototype setattribute (13) - javascript prototype samples (13) - prototype javascript onclick (12) - prototype child node (12) - prototype get child nodes (12) - ajax PeriodicalUpdater example (11) - examples of prototype (11) - prototype json php (11) - javascript prototype tutorial (11) - javascript iterate childnodes (11) - prototype behaviour (11) - ajax.responders (10) - foreach javascript prototype (10) - prototyping javascript (10) - prototype set onclick (10) - Ajax.PeriodicalUpdater tutorial (10) - javascript prototype add child (10) - prototype iterate (10) - javascript xmlnode (9) - prototype javascript samples (9) - example of prototype (9) - prototype addattribute (9) - onCreate prototype (8) - javascript DOM getChild (8) - prototype add onclick (8) - javascript DOM iterate children (8) - add child element prototype (8) - understanding javascript prototype (7) - prototype javascript (7) - childNodes prototype (7) - prototype examples javascript (7) - javascript each prototype (7) - javascript prototypes (7) - javascript iterate child nodes (7) - js prototype examples (7) - javascript childnodes prototype (7) - PeriodicalUpdater tutorial (7) - prototype set attributes (7) - php prototype tutorial (7) - javascript getchildelements (7) - prototype convert to integer (7) - prototype javascript for each (7) - javascript prototype delay (7) - add attribute prototype (7) - javascript addChild (7) - prototype getchildren (7) - prototype foreach (6) - javascript childnodes foreach (6) - json php prototype (6) - javascript prototype each (6) - getChild javascript (6) - setattribute in prototype (6) - prototype iterate json (6) - prototype convert string to number (6) - addAttribute prototype javascript (6) - javascript iterate children (6) - prototype AJAX.PeriodicalUpdater (5) - Prototype Ajax example (5) - prototype javascript example (5) - prototype javascript setAttribute (5) - javascript prototype sample (5) - using prototype with php (5) - understanding prototype in javaScript (5) - prototype get child element (5) - javascript prototype children (5) - php json prototype (5) - prototype each (5) - prototype get child node (5) - jquery periodicalupdater (5) - javascript setAttribute Prototype (5) - prototype PeriodicalUpdater tutorial (5) - best prototype examples (5) - prototype convert string to integer (5) - jscript prototype (5) - delay prototype javascript (5) - prototype iterate children (5) - prototype setAttributes (5) - set attribute prototype (5) - addChild prototype (5) - prototype AJAX responders (4) - prototype Ajax.PeriodicalUpdater example (4) - prototype onclick javascript (4) - prototype with php (4) - prototype each child (4) - prototype javascript click (4) - prototype Ajax.Responders (4) - prototype each examples (4) - prototype delay javascript (4) - javascript prototype addchild (4) - javascript iterate over children (4) - prototype PeriodicalUpdater reset (4) - javascript prototype integer (4) - prototype add child elements (4) - prototype child element javascript (4) - PeriodicalUpdater examples (3) - understanding javascript prototypes (3) - prototype php examples (3) - javascript prototype.onclick (3) - prototype add child node (3) -