Custom eventing with jQuery

Saturday, Jan 31, 2009 2 minute read Tags: jquery javascript
Hey, thanks for the interest in this post, but just letting you know that it is over 3 years old, so the content in here may not be accurate.

Last Thursday I attended a session through Victoria.NET on jQuery hosted by Damian Edwards.

It was a good beginner session on jQuery, I was familiar with most of it but there were a few sweet little gems shown.

During the session when Damian was talking about eventing with jQuery someone asked him a question about doing custom events. Damian wasn't sure how to go about this, or if it was possible.

Well it is possible and I'll go over how to achieve it.

Because of jQuery's nature it's very easy to add custom events to both dom objects and custom objects.
jQuery has lots of events built in, via the click(), keydown(), etc. But ultimately they all implement the bind() method. The just provide click, keydown, etc as the type argument of the method.

But bind() can take anything as a type argument, try this:

$('p').bind('HelloWorld', function() { 
  alert('Hello World event called'); 
});

Now all <p /> tags on the page have an event called HelloWorld which is just waiting to be called, so how do we do that?

$('a').click(function() {
  $('p').triggerHandler('HelloWorld');
});

Yep, the triggerHandler() method will call any of the event handlers which are bound to the objects in the selector.

Obviously this is a bit of a sanitised example, doing that on all elements isn't exactly useful. But it does show that it can be done. With more powerful selectors it's quite possible to set up events similar to using the $addHandler() method within the ASP.NET AJAX library, like is done within the controls in the AJAX Control Toolkit.

It also means that it would be quite possible to set up a Client Event Pool similar to what I talked about in the recent post Fun with a Client Event Pool and modal popups.