Prototype's Shortcuts

Prototype is a wonderful javascript library written by Sam Stephenson.

The more I use it, the more I love it, it makes writting javascript so less painful.

This post is the first of a series aiming to discover its
features.

So let’s start with the lovely shortcuts provided by Prototype.

Shortcuts are functions whose names are as concise as possible, mostly 1 or 2 letters and wrap some of the most repetitive tasks you end up to write when doing javascript.

  • The $() function :
    This little gem is a shortcut to the overused document.getElementById() of the DOM. So just like the DOM method, $() returns the element that has the id passed as arguments.
    But it extended it as well by letting you passed more than one id and $() returns you an Array object containing all the requested elements. Another interesting functionality is that you can pass it either a string or the element itself.
h4. Exemple :
  var myElement = $('content'); 
  // myElement contains the element with id 'content'

  var myElements = $('content', 'content1', 'content2'); 
  // myElements is an Array containing elements with ids 'content', 'content1' and 'content2'
 
  • The $F() function :
    This other little function is a shortcut to get the value of any field input control such as text boxes or drop-down lists. As with $(), it is possible to pass either the element id as string or the element itself.
h4. Exemple :
 var firstname = $F('firstName');
 // firstname now contains the value of the input field with 'firstName' as id
 
  • The $A() function :
    This function turns the single parameters it receives into an Array object. Even if it seems a little strange at first glance, this function combined with Prototype extensions to the Array object allows extremely powerful operations.
h4. Exemple :
 function myFunction() {
   // Let's make an Array from arguments passed to function
   var options = $A(arguments);
   while ( options.length > 0 ) {
     alert( options.shift() );
   }
 }

 myFunction('Hello', 'there', "How's going ?");
 
  • The $H() function :
    This function turns any associative array into an enumerable Hash. One more time add this little function with additions to Hash from Prototype and you’ll soon discover another great feature of the library.
h4. Exemple :
 function turnIntoQueryString( params ) {
   var hashParams = $H(params);
   alert( hashParams.toQueryString() ); 
 }

 var a = [];
 a['firstname'] = 'Jonathan';
 a['lastname'] = 'Tron';
 a['subscribe'] = 1;

 turnIntoQueryString(a); 
 // Display : firstname=Jonathan&lastname=Tron&subscribe=1 
 
  • The $R() function :
    This function is a little more tied to Prototype than previous ones. It’s a shortcut to the expression new ObjectRange(start, ends, excludeBounds). I will discuss the ObjectRange object in another post.
h4. Exemple :
 // Let's create an ObjectRange going from 10 to 30 and including those bounds
 var myRange = $R(10, 30, false);

 // Now we can for exemple iterate through values with iterator functionality provided by Prototype
 myRange.each( function(value, index) {
   alert(value);
 });
 
 // Or check if our lovely user enter a good value about his house's loan duration. 
 myRange.include( $F('loanLength') );
 
  • Try.these() function :
    This function let you ‘try’ any number of functions calls, returning the value from the one which works.
    This is convenient to handle differences between browsers DOM implementations.
h4. Exemple :
 // This function is a convenient way to  get an XMLHttpRequest Object
 // Whatever browser executes the script
 function getAjaxTransport() {
   return Try.these(
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')},
      function() {return new XMLHttpRequest()}
    ) || false;
 }
 

The previous shortcuts are included into current stable release 1.4.0… The next one is only available in the trunk version (aka 1.5.0pre).

  • $$() function :
    This shiny new function is a shortcut to select some elements with a CSS-like syntax,
    just like the Behaviour Javascript Library does with its selectors.
h4. Exemple :
 // Following exemple taken from Prototype Changelog

 // Find all <img> elements inside <p> elements with class "summary",
 // all inside the <div> with id "page". Hide each matched <img> tag.

 $$('div#page p.summary img').each(function(e) {
   e.hide();
 });
 

So here it is for the first post about Prototype.

Feel free to correct any of my mistakes.

Fri, 20 Jan 2006 11:17 Posted in

  1. By Justin Turner 13/08/2007 at 00h05


    Excellent list. Thanks!

  2. By lomakin 14/10/2008 at 14h12


    Thank you. Very useful! :-)

Comment Prototype's Shortcuts


RSS