Skip to content

October 4, 2009

Ajax/Prototype: Use onComplete to separate Javascript client code from HTML page

by Joe Kuan

PrototypeSuppose that you use Ajax.Updater to update the HTML content inside a DOM element. Usually, the HTML forms or table entries require a bit of embedded Javascript code for the event handlers. However, using the onComplete property can give a nice separation between the HTML page and Javascript code.

Here is an example of an HTML page with psuedo code of embedded event handlers

<FORM name=pizza_menu id=pizza_menu>
    Pizza: <SELECT name=price onChange='updatePrice($("pizza_menu"));'>
              <OPTION value=9.99>Large Pepperoni</OPTION>
              <OPTION value=6.99>Medium Peperroni</OPTION>
              <OPTION value=3.99>Small Pepperoni</OPTION>
              </SELECT><BR/>
    Price each: <SPAN ID=price_each ></SPAN><BR/>
         Quantity: <SELECT name=quantity onChange='updatePrice($("pizza_menu"));'>
              <OPTION value=1>1</OPTION>
              <OPTION value=2>2</OPTION>
              <OPTION value=3>3</OPTION>
            </SELECT><BR/>
    Total: <SPAN ID=total></SPAN><BR/>
    <INPUT TYPE=button name=order value=Order onClick='order($("pizza_menu"));'>
</FORM>

Then call Ajax.Updater(‘menu’, ‘menu.html’)

Alternatively, we can separate the Javascript and HTML as

Ajax.Updater('menu', 'menu.html', {
       onComplete: function (t) {
           $('pizza_menu').price.onChange =
           $('pizza_menu').quantity.onChange = function ( ) {
              updatePrice($(&amp;quot;pizza_menu&amp;quot;));
           };

           $('pizza_menu').order.onClick = function ( ) {
              order($(&amp;quot;pizza_menu&amp;quot;));
           }
       }

DOM ScriptingThe menu.html can remain as pure HTML code without any Javascript. This kind of approach is also encouraged in the book, “DOM Scripting, Chapter 5, Best Practices”. Arguably, this is a matter of personal preference but I personally found it useful especially in the conditions of using Ajax.Updater.

I work for iTrinegy and here are my other Prototype blogs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

%d bloggers like this: