Prototype Changes

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

  • Shorter syntax for event handling
    $('element').observe('click', function(e) {  alert(e); });
    
  • Make destructive Element, Form, and Form.Element methods return their first argument, so that multiple calls can be chained together.
    $(“sidebar”).addClassName(“selected”).show();

    The following methods now return their first argument: Element.toggle, Element.hide, Element.show, Element.remove, Element.update, Element.replace, Element.addClassName, Element.removeClassName, Element.observe, Element.stopObserving, Element.cleanWhitespace, Element.scrollTo, Element.setStyle, Element.makePositioned, Element.undoPositioned, Element.makeClipping, Element.undoClipping, Form.reset, Form.disable, Form.enable, Form.focusFirstElement, Form.Element.focus, Form.Element.select, Form.Element.clear, Form.Element.activate, Form.Element.disable, Form.Element.enable.

  • Form and Form.Element methods mixed in to $ and $$
  • For consistency, Element.toggle, Element.show, and Element.hide no longer take an arbitrary number of arguments.

    !! BACKWARDS COMPATIBILITY CHANGE !!

    If you have code that looks like this: Element.show(‘page’, ‘sidebar’, ‘content’); You need to replace it with code like this: [‘page’, ‘sidebar’, ‘content’].each(Element.show);

  • Mix in Form and Form.Element methods to forms and form field elements with $() and $$(). Closes #4448. [Dan Webb, sam]
  • Add Object.clone
  • Add Form.Element.disable and Form.Element.enable. Closes #4943.
  • Field is now simply an alias for Form.Element.
  • Add Element.Methods.getElementsByClassName and Element.Methods.getElementsBySelector. Closes #4669.
  • Avoid race condition when stopping an Ajax.PeriodicalUpdater. Closes #4809.
  • Improve support for synchronous requests. Closes #5916.
  • Add serialization and observation support for input type=search. Closes #4096.
  • Properly decode query components in String.prototype.toQueryParams. Closes #3487.
  • Add Array.prototype.reduce:
    • [1, 2].reduce() // [1, 2]
    • [1].reduce() // 1]
    • [].reduce() // undefined]
  • Add Object.keys and Object.values
  • Simulate non-GET/POST requests by POSTing with a _method parameter set to the actual verb
  • Make Element.update() handle TABLE-related elements with the DOM API because of IE’s missing .innerHTML property on them
  • Sync to script.aculo.us unittest.js library as of 2006/08/29
  • Add additional unit tests to test/unit/dom.html for testing Element.update and $().update in various enviroments
  • Prevent possible exceptions on unloading the page in IE

I’m psyched!

Speeding Up Prototype’s $$ Selector

prototype.gif 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.

Here’s a simple example that we use at MasterWish:

mw_b.prototype.checkAll = function()
  {
    $$('.buddy_checkbox').each(function(e){e.checked=true;});
  };

All that example does is iterates over all elements in the DOM that have the class buddy_checkbox and sets their checked value to true. Short and sweet. However, with version 1.5 of Prototype, it could be dog slow at times with more complex selector queries.

I was ecstatic when I found (via Ajaxian) that Sylvain Zimmer has sped up the $$ function quite a bit. I implemented it in the test area of MasterWish and have been very pleased with the results! Here’s what Sylvain has to say on his mod:

Prototype’s current code is quite elegant (as always!) but very slow, so I wrote an add-on that makes this function up to 20 times faster in most usual cases (tested on IE6, Firefox 1.5 and Opera).

[…]

Here are the main ideas of this add-on :

  • Forwarding the call to the old $$ if the selector expression is too complicated (currently : if it uses attributes)
  • Replacing regular expressions with a simple parser
  • Minimizing the number of operations done on each iteration.
  • Trying to use getDocumentById() instead of getDocumentByTagName() when possible.
  • Avoiding recursive functions with return values.
  • Not being afraid of some “old-style” code if it speeds up the execution ;-)

All you need do is get his mod and include it in a script tag after the Prototype inclusion. Simple as that!

Script.aculo.us v1.6 Released

Great news over at Mir.aculo.us. It appears as if version 1.6 of my favorite DOM manipulation library, Script.aculo.us has been released! Thankfully the new version of Script.aculo.us uses Prototype v1.5.

This is sexy because now I can revert to downloading both Prototype and Script.aculo.us right from the Script.aculo.us site. (Hooray for being lazy)

Here’s an excerpt from the original post:

script.aculo.us 1.6 marks the switch over to Prototype 1.5 (1.4 will no longer be supported), which has really great new features and has undergone some refactoring to take advantage of the Prototype 1.5 niceties.

Other new stuff includes window-scrolling while dragging, performance optimizations and various bug fixes.

They are urging people to test out 1.6. Get on it!

MasterWish – Practicing What I Preach

masterwish MasterWish, my labor of love (created with my friends Zach Tirrell and Jon Emmons) is my playground for Ajax and Web 2.0 experiments.

If you haven’t been acquainted with the site, its a wishlist site with a schlew of features. The high point is the ability to secure down lists and grant access to specific buddy groups. I’m pleased to say that we have gained a decent member base in the past 8 months and I am also happy to say that things are going to change around shortly!

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.

Things are changing. I have begun the work to implement the following:

  • Creation of more “hackable” Web Service APIs using SOAP and REST
  • Representation of data using both XML and JSON
  • Ajax powered by Prototype
  • Sweet DOM manipulation powered by Script.aculo.us
  • Separation of Layout and Logic with event:Selectors
  • and of course, we’re already doing: Server-Side Templating for greater separation of Layout and Logic.

Sign up. Stay tuned. Get gifts.

Writing Your Server-Side Ajax Handler

[[innerindex]]In my recent post on ‘Ajax; Templating; and the Separation of Layout and Logic,’ I refer to an Ajax Handler that sits server side to handle Ajax calls. Some elaboration is in order.

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 is portable.

Set up your Functions

Before you create a handler, you need a set of functions that the handler can reference. Here’s an example:

< ?php
function world($params='')
{
  return 'Goodbye Cruel World.';
}//end world

function sweetWorldAction($params='')
{
  //we expect params to be an array or a string similar to a parameter string from a GET..i.e. "bork=asdf&cheese=yes please"
  //parse out the variables
  if(!is_array($params))
  {
    parse_str($params,$params);
  }//end if

  //do your logic here
}//end sweetWorldAction
?>

Now that we have the functions all set, we’ll set up a handler that receives Ajax calls and calls the appropriate functions.

The Eval Method – A Dynamic Handler

This method is one that I toyed around with for a while and I’ll admit that its pretty simple and clean but there are some drawbacks. We’re going to make a few assumptions: All requests will be GET (this is to keep things simple for this example) and we will keep the complexity of .htaccess sweetness out of these examples and assume that each call will be passing a function variable that specifies the function we are calling. I’ll get to those in a second…but first I’ll show you the handler code in this Eval Method:

< ?php
//if the user leaves the page or closes the browser prematurely, this will help prevent half completed statements
ignore_user_abort();

include('functions.php');

//list out your Ajax accessible functions
$valid_functions = array('world','sweetWorldAction');

if($_GET['function'] && in_array($_GET['function'],$valid_functions))
{
  //get the get parameters
  $params = $_GET;  
  //unset the function index from the params because we just don't need it there
  unset($params['function']);

  //build your parameter string:
  $param_string='';
  foreach($params as $key=>$param)
  {
    $param_string.=(($param_string)?'&':'').$key.'='.$param;
  }//end foreach

  //make your function call
  eval($_GET['function']."('$param_string');");
}//end if

?>

The Variable Variable Method – A Dynamic Handler

This method (compliments of PHPDeveloper) is simpler than the Eval Method and just as dynamic.

< ?php
//if the user leaves the page or closes the browser prematurely, this will help prevent half completed statements
ignore_user_abort();

include('functions.php');

//list out your Ajax accessible functions
$valid_functions = array('world','sweetWorldAction');

if($_GET['function'] && in_array($_GET['function'],$valid_functions))
{
  //get the get parameters
  $params = $_GET;  
  //unset the function index from the params because we just don't need it there
  unset($params['function']);
  //make your function call
  $_GET['function']($params);
}//end if

?>

The Switch Method – A Basic Handler

This method handles each call individually. The reason for using switch rather than if-elses is simply because your application will most likely possess a large number of Ajax-ified functions and those if-elses would be ghastly to read and decrease performance…the Switch statement is much cleaner.

< ?php
//if the user leaves the page or closes the browser prematurely, this will help prevent half completed statements
ignore_user_abort();

include('functions.php');

if($_GET['function'])
{
  switch $_GET['function']
  {
    case 'world':
      echo world();
      exit;
    break;
    case 'sweetWorldAction':
      echo sweetWorldAction();
      exit;
    break;
  }//end switch
}//end if

?>

Make a Choice

Which are you going to use? While the Eval and Variable Variable Methods contain very small amounts of code in the handlers, the logic has simply been shifted to the functions themselves. Increased Ajax-geared logic within the functions themselves reduces portability. However, in the Switch Method, logic is organized in a fairly easy to follow manner while making use of very generic functions that can be used in multiple fashions. Obviously, the Switch Method is my preferred choice :)

In Closing

Handler scripts make the Ajax magic happen and the separation of handler logic from your application logic is just as important for robust development and debugging as the need for separation of layout and logic. Play around with the above methods and see which works for you. If you have a method all your own, I’d be interested to hear it!

Oooo event:Selectors for Prototype

event_selectorsMy article on the Separation of Layout and Logic touched on a key point of heavy Javascript use in an Ajax rich environment…the need for separation of Javascript code – namely events – from the HTML. Behaviour was my suggested CSS/Javascript event selector framework.

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.

  • event:Selectors is dependant on Prototype which reduces code duplication.
  • It has reduced the layer of complexity of event selecting by one layer of abstraction.
  • The framework allows concatenation of CSS elements for event assignment.
  • Lastly, its added a loaded event that is triggered when an element loads.

Here’s an example of Behaviour event handlining:

  var rules = {
    '#item li': function(element) {
      Event.observe(element, 'click', function(event) {
        var element = Event.element(element);
        element.setStyle('color': '#c00');
      });
    },
    
    '#otheritem li': function(element) {
      Event.observe(element, 'click', function(event) {
        var element = Event.element(element);
        element.setStyle('color': '#c00');
      });
    }
  };
  Behaviour.register(rules);

Here’s the equivalent in event:Selectors:

  var Rules = {
    '#item li:click, #otheritem li:click': function(element) {
      element.setStyle('color': '#c00');
    }
  };

EventSelectors.start(Rules);

Simplification makes me happy. I’m a convert.

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
});

Prototype Cheat Sheets

prototype.gifThe guys over at Ajaxian alerted me to this sweet resource. Jonathan Snook has created a graphical (and quite attractive) Prototype cheat sheet.

As I have stated in the past, I develop web applications for Plymouth State using the Scriptaculous which is built on top of Prototype Javascript Framework. I often find myself referring back to the Scriptaculous Wiki to simply help me remember a function name of a Prototype object. Well, the cheat sheet that Jonathan has created will now live on my wall for those quick references! If you are an avid user of Prototype, check these suckers out.

Script.aculo.us Is My New Best Friend

Ajax is great. DOM manipulation is sexy. I’m fairly new to the Ajax world having only developed with with it since July. MasterWish was my guinea pig and continues to be my playground for all things Web 2.0. Luckily, my manager Ken is pumped up about this whole Web 2.0/Ajax thing which has allowed me to experiment with my projects at work as well and PSU should expect to see some sweet apps roll out over the next year!

Since July, I’ve been developing my Ajax applications and examples using SAJAX (Simple Ajax), a PHP/Javascript framework for Ajax development. It was great at first glance…a lot easier than building Asynchronous Javascript transactions from scratch. But despite its ease, it was a bit clunky. Last week I was stumbling around the web looking for anything new to suck up and found a beauty of a tool. Script.aculo.us.

Script.aculo.us is a Javascript Effects and Control framework developed by Thomas Fuchs, a software architect living in Vienna, Austria who, like me, was disappointed by current web application frameworks that made no sense to him. His framework is 3 things: Easy to Use, Simple, and Easy to Use. His libraries – built off of the Ajax framework, Prototype – blow SAJAX out of the water! Let me give you an example to, say, update a news title on an article (I won’t include the HTML markup as that is trivial):

Here’s what needs to be done to build a SAJAX call:

Step 1: Create a SAJAX Call Function

function x_updateTitle()
{
	sajax_do_call('/process_ajax.php',"x_updateTitle", x_updateTitle.arguments);
}

Step 2: Create a server side function to handle the update

< ?php
function x_updateTitle($news_id,$news_title)
{
	//do some database calls to update the title;
}
?>

Step 3: Edit the server side SAJAX file (process_ajax.php) and add x_updateTitle to the list of valid call functions

< ?php
include('sajax.php');
addFunctions('x_updateTitle');
handleClientRequest();
?>

Step 4: Call the SAJAX Javascript function from somewhere (in an onClick, onSubmit or something)

<a onClick="x_updateTitle(1, document.getElementById('news_title').value, 'callbackFunction');">asdfdf</a>

Here’s the equivalent in Script.aculo.us
Step 1: Create a server side function to handle the update

< ?php
function x_updateTitle($news_id,$news_title)
{
	//do some database calls to update the title;
}
?>

Step 2: Call the Script.aculo.us Javascript function from somewhere (in an onClick, onSubmit or something)

<a onClick="new Ajax.Request('/process_ajax.php', { asynchronous:true, parameters:'news_id=1&news_title=$(\'news_title\')', onSuccess:callbackFunction });">asdf</a>

Thats it! Its a big difference. Thats just the tip of the iceberg. Script.aculo.us has many features for implementing Drag and Drop with one line of Javascript code; fancy display/hide functions; dynamic DOM Element creation/deletion; field autocompletion; and various other visual effects. It slick. And to top it off, the Script.aculo.us website is pretty sweet! Luckily the documentation is excellent and is in wiki format. As Plymouth State moves into the Web 2.0 world, I’ll be pushing for Script.aculo.us/Prototype to be our Ajax standard. I have seen the light and it is good.