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 (372) - Prototype samples (279) - prototype setattribute (252) - prototype onclick (120) - prototype set attribute (90) - Ajax.PeriodicalUpdater example (70) - php prototype (70) - prototype childnodes (69) - prototype javascript examples (63) - prototype children (58) - setAttribute prototype (57) - javascript prototype (52) - prototype PeriodicalUpdater (51) - prototype child (40) - Ajax.Responders.register (37) - javascript prototype foreach (37) - prototype add attribute (35) - javascript foreach prototype (34) - prototype php (34) - prototype example (34) - prototype add child (32) - periodicalupdater example (28) - javascript getchild (28) - prototype get child (26) - prototype addchild (26) - prototype (25) - javascript prototyping (24) - javascript prototype examples (23) - javascript prototype onclick (22) - javascript prototype example (22) - ajax prototype examples (21) - prototype onCreate (20) - prototype and php (20) - prototype child nodes (20) - prototype childnode (20) - prototype PeriodicalUpdater example (19) - prototype javascript sample (19) - prototype ajax examples (18) - prototype add child element (18) - prototype javascript foreach (17) - prototype getchild (17) - javascript prototype json (16) - Ajax.PeriodicalUpdater sample (14) - javascript onclick prototype (13) - javascript prototype samples (13) - prototype get children (13) - Ajax.PeriodicalUpdater examples (12) - javascript prototype setattribute (12) - javascript foreach childNodes (12) - prototype javascript onclick (12) - onclick prototype (12) - samples prototype (12) - PeriodicalUpdater prototype (11) - prototype child node (11) - examples of prototype (11) - prototype json php (11) - prototype get child nodes (11) - javascript prototype tutorial (11) - ajax.responders (10) - ajax PeriodicalUpdater example (10) - prototype set onclick (10) - Ajax.PeriodicalUpdater tutorial (10) - javascript iterate childnodes (10) - prototype behaviour (10) - javascript prototype add child (10) - javascript xmlnode (9) - example of prototype (9) - prototyping javascript (9) - prototype iterate (9) - javascript DOM getChild (8) - prototype add onclick (8) - prototype addattribute (8) - onCreate prototype (7) - prototype javascript (7) - childNodes prototype (7) - prototype examples javascript (7) - prototype javascript samples (7) - javascript prototypes (7) - javascript iterate child nodes (7) - js prototype examples (7) - javascript childnodes prototype (7) - php prototype tutorial (7) - javascript DOM iterate children (7) - add child element prototype (7) - javascript prototype delay (7) - javascript addChild (7) - javascript childnodes foreach (6) - json php prototype (6) - getChild javascript (6) - foreach javascript prototype (6) - prototype iterate json (6) - prototype set attributes (6) - prototype convert string to number (6) - javascript getchildelements (6) - prototype javascript for each (6) - add attribute prototype (6) - prototype AJAX.PeriodicalUpdater (5) - Prototype Ajax example (5) - understanding javascript prototype (5) - prototype javascript example (5) - prototype foreach (5) - javascript prototype sample (5) - using prototype with php (5) - understanding prototype in javaScript (5) - javascript prototype children (5) - php json prototype (5) - prototype each (5) - prototype get child node (5) - jquery periodicalupdater (5) - setattribute in prototype (5) - javascript setAttribute Prototype (5) - prototype PeriodicalUpdater tutorial (5) - PeriodicalUpdater tutorial (5) - prototype convert string to integer (5) - jscript prototype (5) - delay prototype javascript (5) - prototype convert to integer (5) - prototype setAttributes (5) - prototype getchildren (5) - addAttribute prototype javascript (5) - javascript iterate children (5) - prototype AJAX responders (4) - prototype Ajax.PeriodicalUpdater example (4) - javascript prototype each (4) - prototype get child element (4) - prototype onclick javascript (4) - javascript each prototype (4) - prototype with php (4) - prototype each child (4) - prototype Ajax.Responders (4) - best prototype examples (4) - prototype each examples (4) - prototype iterate children (4) - prototype delay javascript (4) - prototype PeriodicalUpdater reset (4) - javascript prototype integer (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) - prototype sample javascript (3) - prototype example php (3) - example PeriodicalUpdater (3) - php prototyping (3) - prototype javascript click (3) - prototype php json (3) - prototype $$ examples (3) -