Custom eventing with jQuery

31 January 2009 · 2 minute read · jquery · javascript

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() {

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.

Published: 2017-10-23 19:16:31 +1100 +1100, Version: 7c4a504