jQuery Events - Beyond the DOM

Since demos are more fun than paragraphs, take a look at MicroTest, a tiny illustration using custom jQuery events and triggering them on plain JavaScript objects.

Custom Events

jQuery lets you bind and trigger custom events on DOM elements. This is used in jQueryUI to expose a number of custom events for their widgets. The jQueryUI tab component will fire a tabsselect event when you click on a new tab:

$('#tabs').tabs();
$('#tabs').bind('tabsselect', function(event,ui){ 
  console.log('Selected a New Tab', event, ui) ;
});

Now every time a new tab is selected, the event will be logged to the console. With either WebKit's inspector or FireBug, you can go to jQueryUI's tab demo and try it for yourself.

Events on Plain JavaScript Objects

What if you have plain objects that you would like to trigger events on? It turns out that you can use jQuery's custom events on any JavaScript object. You could for instance create a clock that will repeatedly fire tick events:

function Clock(interval){
  var self = $(this);
  var i = 0;
  setInterval(function(){
    self.trigger('tick', i++);
  }, interval);
}

// will trigger a tick event every 1/2 second
var clock = new Clock(500);

// Listen to the clock:
$(clock).bind('tick', function(event, i){
  console.log('Clock has ticked',i,'times');
});

Go ahead and try the example above in your console. Now that you've seen examples of custom events and binding to custom objects, take a look at the MicroTest example again, and you should see how it all fits together.

If you are ever tempted to roll your build event library, but are already using jQuery, this might save you some time and hassle.

blog comments powered by Disqus
Monkey Small Crow Small