At the Forge - Unobtrusive JavaScript

Remove JavaScript event handlers from HTML files using Prototype and Lowpro.
Events in Prototype and Lowpro

Our event handlers are now unobtrusive. However, there still are some problems associated with them. For example, what happens if we want to assign multiple handlers to a single event? That is, what if we want to execute not one function, but two, for $('hyperlink').onclick? In our current paradigm, we don't have any options; to have two functions execute, we need to wrap them both into a single function and then make that single wrapper function the event handlers.

This isn't much of a solution, particularly if we are loading third-party libraries that might want to attach handlers to one or more events. Instead, we need to use a different paradigm—one that lets us attach a handler to an event, rather than set the handler.

Prototype lets us do this with the observe method, which is available to any extended element—including those returned by the $() and $$() functions. So, we can say:

$('hyperlink').observe('click', show_x_and_y);

Because of the way that Prototype's observe method works, we can attach multiple handlers to a single event:

$('hyperlink').observe('click', show_x_and_y);
            function() { alert('yay!'); return false;});

Of course, because this code still depends on the existence of $('hyperlink'), we still need to wrap it in a function that is then attached to window.onload. (We also can attach our function to the dom:loaded event, which fires before window.onload, but the idea is the same.)

An alternative solution is to use the Lowpro JavaScript library, which provides functions that facilitate easier writing of unobtrusive JavaScript.

By loading lowpro.js (after Prototype, but before any code that will use Lowpro), we gain access to the Event.addBehavior method, which lets us attach one or more events to any CSS selector. Listing 6 is a slight rewrite of our HTML file to include lowpro.js, and Listing 7 shows how we can set our event handlers using Event.addbehavior:

     '#hyperlink:click' : show_x_and_y,
     '#hyperlink:mouseover' : function() { $( 'the_form' ).hide() },
     '#hyperlink:mouseout' : function() { $( 'the_form' ).show() }

We see that Event.addBehavior is a function that takes a single parameter, a JavaScript object (which we can think of as a hash). Each of the object's keys combines a CSS selector (#hyperlink in this case) with the name of an event, with a colon separating the two. Note that the event name does not include a leading “on”. So what would be the onmouseover handler is called mouseover for Event.addBehavior.

As you can see in Listing 7, Event.addBehavior automatically wraps our event-handler definitions in code that waits for the entire page to load. So, we no longer need to set document.onload, for example.

Finally, the CSS selector code means we can set events on multiple elements simultaneously. If we want all paragraphs, or all table headers or even all images, we can do that quickly and easily with Lowpro. Lowpro allows us to reduce the amount of event-handling code that we write dramatically, keeping it in a single location and removing it from the HTML file where we might have first considered putting it.

I should add that Lowpro used to include DOM-manipulation routines as well, allowing us to add and modify page elements using a variety of convenience functions. However, recent versions of Prototype include this functionality already, allowing Lowpro to stick to behavior not addressed by Prototype.



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

So interresting...

Arimbourg's picture

Thanks for this article. Clear and so usefull...

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState