Custom events in JQuery

For a project at work this week I needed to modify a Javascript library so that under a particular condition it would generate a JS event that could be handled elsewhere in the application.  Why use JS events rather than just call a regular JS function? Well, I guess partly to maintain consistency with the way that other events are handled within the app, and partly because it’s a more elegant solution: When an event is thrown, if there’s nothing to catch and handle the event it doesn’t matter but when you call a JS function you need to be sure that the function exists otherwise you’ll end up with JS errors on the page so you have to first test that the function exists before you call it. Also an event can propagate up through the ancestory of objects on your page so it can be handled at whichever level is most appropriate or handled in different ways at different levels.

In JQuery the syntax for creating an event handler is exremely simple, for example, given the following HTML:
[code lang="jscript"]

Click me!

[/code]

…the JQuery code to handle for the click event would be:

[code lang="jscript"]
$('#container').click(function() {
alert('You clicked me!');
});
[/code]

In the above example, the “click” method is a shorthand utility method provided by JQuery, but is the same as:

[code lang="jscript"]
$('#container').bind('click', function(e) {
alert('You clicked me!');
});
[/code]

There’s a whole bunch of standard HTML events that the browser may generate in response to user input (and that can be handled in similar fashion). You can also get JQuery to generate these events programatically.

It turns out that you can create a handler for your own custom event in exactly the same way, just change the name of the event (“click” in the example above), to the name of the event you want to create and be sure to use the longhand “bind” method. E.g.

[code lang="jscript"]
$('#container').bind('myEvent', function(e) {
alert('My event just fired');
});
[/code]

Then, when you want to trigger this event, use the err… “trigger” function:

[code lang="jscript"]
$('#container').trigger('myEvent');
[/code]

Because we’re using events rather than a straight method call (and JQuery 1.3 or later) we could write another handler for myEvent but on an ancestor of #container – the document body in this case. The handlers would be called in order, first on #container, then on the body. If we want to prevent the event from bubbling up through the DOM we can kill it with the stopPropagation() function:

[code lang="jscript"]
$('#container').bind('myEvent', function(e) {
e.stopPropagation();
alert('My event just fired');
});
[/code]

I was surprised by just how simple this was once I realised that the process for custom events is exactly the same as that for standard browser events.

Leave a Reply