Using jQuery events for triggering complex UI updates

Nowadays jQuery become a very standard library used in in 90% of all projects. Simplicity of DOM manipulation with cross browser capability attracts all developers, from newbies to profs.

While developing AJAX UI with many forms nested in each other I faced a problem of not well written code, what was a real pain to modify.

I am going to tell how jQuery events saved my ass.

jQuery events are very simple and easy to use, you should have known them like click, hover, submit, etc..

Usage is prety simple thu

But you probaby did not pay much attention to jQuery events documentation  chapter. There is a nice paragraph that says, event name can be any string and events can be triggered by user.

These two facts play important role in what I am going to achieve. See code below.

Usage scenario – AJAX UI

How did this save my ass? I have a complex user interface based on AJAX. That means user clicks on the button and it loads form. Problem is that form also has buttons, tabs and all these DOM elements have to binded to events.

In this case code lookgs ugly:

The more elements and nests levels you have, code looks heavier to modify and support.

I have rewritten same code using jQuery custom events, look here

Code become more flat and structured, much easier to support and add functionality. It is possible to add multiple event handlers and they all will be executed in that order.  It acts  like subscribing.

Using parameters in custom jQuery events

For dessert, nice feature that saves time and global variables. It is possible to pass variables when event is triggered and they will appear as arguments to invokig functions:

Leave a Reply

Your email address will not be published.