DailyJS

jQuery Custom Events

Ric Roberts

Subscribe

@dailyjs

Facebook

Google+

jquery events tips ringo

jQuery Custom Events

Posted by Ric Roberts on .
Featured

jquery events tips ringo

jQuery Custom Events

Posted by Ric Roberts on .

jQuery makes it easy to bind and trigger custom events. Although it's
not immediately apparent from the
documentation
, creating custom
events is simple and very useful.

Binding Custom Events

Events can be bound to DOM nodes like this:

$("#myElementId").bind("myCustomEvent", function(event) {
  alert("myCustom event happened!");
});

Triggering Custom Events

jQuery's trigger function is
used to instigate the event, passing the name of the event as a string
like this:

$("#myElementId").trigger("myCustomEvent");

If you want to pass data to the handler you can use an event
object
:

var myCustomEvent = jQuery.Event("myCustomEvent");
myCustomEvent.usefulInformation = "some data";
myCustomEvent.otherStuff = "some other data";
$("#myElementId").trigger(event);

Namespaces

Another cool feature of jQuery events is
namespacing, which supports triggering or unbinding specific groups of handlers without having to
reference them directly.

You can add a namespace when binding an event which can be referenced
when you unbind or trigger it. It's possible to use multiple namespaces
at once.

$('.myCSSClass').bind('myEvent.myNamespace.myOtherNamespace', function(){alert('namespaced event')}); 
$('.myCSSClass').trigger('myEvent.myNamespace');
$('.myCSSClass').unbind('myEvent.myOtherNamespace');

If you specify a namespace when unbinding or triggering events, you need
to match one of the bound namespaces (or alternatively, if no namespace
is specified it matches everything).

$('.myCSSClass').bind('myEvent.myNamespace', function(){alert('namespaced event')}); 
$('.myCSSClass').trigger('myEvent.myNamespace'); // mentioned explicitly: will trigger
$('.myCSSClass').trigger('myEvent');  // not specified: will trigger 
$('.myCSSClass').unbind('myEvent.differentNamespace'); // won't unbind