At the Forge - Unobtrusive JavaScript

 in
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);
$('hyperlink').observe('click',
            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:

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.

______________________

Comments

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

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix