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.

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

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!

// alerts "1", "2", "3" ... "50"
(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!

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

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:

// add Enumerable to childNodes
var children = $A($("mydiv").childNodes);

// sets class="highlighted" for all child nodes of "mydiv"
children.each(function(child) {
 child.setAttribute("class", "highlighted");
});

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!

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

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.

Ajax.Responders.register({
 onCreate : showLoader,
 onComplete : hideLoader
});

Comments

15 responses to “Prototype Makes Javascript Painless”

  1. […] 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). […]

  2. […] 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. […]

  3. […] 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. […]

  4. […] 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. […]

  5. […] 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. […]

  6. […] 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. […]

  7. […] 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. […]

  8. […] 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 … […]

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

  10. 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.

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

  12. Error in source Avatar
    Error in source

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

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

  13. […] 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. […]

  14. Hello! Good Site! Thanks you! pdsudpanmo

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