Event driven programming with jQuery – (part 3). What is a module?

What is a module in one web page is may be not the correct question. Everything depends on how you understand the module. Let’s assume there is a tab panel on the page. This can be implemented simply by one UL and one DIV. In a sample app just clicking on a LI the the DIV content changes with appropriate content. Such tab panels can be seen almost on every site. See the homepage of Yahoo!. There are at least two tab panels, and to be exact every simple menu is like that, right? You click on an item and something on the page changes.

So a simple tab panel can be a single module and most often it is. But for this example let say the tab panel is composite of two modules. One for the UL > LI tabs and one for the DIV containing the dynamically loaded content.

And now comes the tricky part. What these two modules do, and what they are supposed to do. In one hand the main strategy is to think about them if they must work on a separate pages. If there is one page only with the UL and another with the DIV. They must continue to work correctly.

The one and only task of the UL is to change the style of the selected, currently clicked, LI item and to say to everybody “I was clicked”.

In jQuery the most simple way to say that is by adding some event listeners to the UL > LI part, like so:

$('ul > li').click(function() {

But that’s simply not so event driven for this example. If the DIV is not on the same page this will throw an error. And in a large application this is absolutely possible. There you may have huge modules, each of which make his own things, loads his on data and just sends messages.

So I’m about to change a bit the above code like this:

$('ul > li').click() {
   $(document).trigger('i-was-clicked', [idOfTheLi]);

Of course if not everything is clear up to now, don’t worry, this is only pseudo code. In my next post I’ll show the full working sample app with custom event listeners.

For now is OK just to mention that in jQuery there are functions like .bind and .trigger that do the work. The only developer part is to add some code like:

$(document).bind('tab-clicked', callback);

You can bind and trigger events from whatever DOM element you want, and they act just as if you attach a click or any mouse event.

To clear up things, let’s simulate the click event like so:

in plain jQuery:


That binds the click event on the document and of course it can be triggered with a simple mouse click, but to finish the example let’s say there’s a function, or AJAX call that after load triggers this callback:

   success : function() {
       // on success simulate the document click

That was all pseudo code and the real working example will be in my next post.

Leave a Reply

Your email address will not be published. Required fields are marked *