Skip to content
January 19, 2010 / Thomas Danemar

Global Events with jQuery

Someone over at the jQuery Google group asked if it’s possible to use global events with jQuery, and to have individual elements listen to those events. A scenario could be to have a div update its content when a global update event is triggered.

This is certainly possible, but the solution is perhaps not entirely obvious. As you may know, you can use jQuery’s trigger function to trigger events on any object. The easiest way to implement global events is to just trigger an event on the global document object:

$(document).trigger("myCustomEvent");

And then listen to it with bind():


$(document).bind("myCustomEvent", function() {
   //code to execute when event triggers
});

Tinkering with the global document object is a bit icky though, and may even make Doug Crockford come over to your house and beat you with a stick. Better to use a dedicated object to hold your events, app.eventHolder, or whatever you feel like calling it.

Either way, having individual elements listen to these global events isn’t difficult, but there’s no dedicated function for it, and scoping it right may be tricky. I made a tiny plugin to help with this:

$.fn.bindToGlobalEvent = function(eventName, func) {
   $(app.eventHolder).bind(eventName, this, function(e) { func.call(e.data);
});

That’s all it takes, really. With this plugin, you could for example have a div change content when a global even triggers like so:

$("#someDiv").bindToGlobalEvent("myCustomEvent", function() {
   $(this).html("I was updated!");
});

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: