Documentation

Namespaced Events

From jQuery JavaScript Library

Jump to: navigation, search

jQuery provides a system for namespacing bound events for easier triggering and removal. Namespaced events were added in jQuery 1.2.

The Problem

Generally, when binding an event callback, you would do something like:

$('.class').bind('click', function(){});

However, there is a problem: Sometimes you want to unbind just a specific handler, or group of handlers (like all handlers bound by a plugin).

Unfortunately calling unbind will remove all bound handlers.

$('.class').unbind('click');

You could create a reference for the function and use that for both bind and unbind.

function handler() { ... }
$('.class').bind('click', handler);
$('.class').unbind('click', handler);

But that requires that you maintain a reference to the function for as long as it exists - which isn't always feasible.

The Solution: Namespaced Events

jQuery provides a concept called namespaced events: Simply add a classname to your event when you declare it. You can then reference that namespaced event both with unbind and trigger.

$('.class').bind('click.namespace', function(){}); 
$('.class').trigger('click.namespace');
$('.class').unbind('click.namespace');

Namespaced events will be unbound or triggered when their namespace is mentioned explicitly, or no namespace is mentioned at all. For example:

$('.class').bind('click.namespace', function(){}); 
$('.class').trigger('click.namespace'); // Will trigger
$('.class').trigger('click');           // Will trigger
$('.class').trigger('click.other');     // Won't trigger

If you've used the same namespace on multiple events, you can easily remove the bindings from all events at once.

$('.class').bind('click.namespace', function(){});
$('.class').bind('blur.namespace', function(){});
$('.class').unbind('.namespace');

Namespaces may also come in handy when reinitializing events after an Ajax request:

$('.class')
  .unbind('click.namespace')
  .bind('click.namespace', function(){});

As of jQuery 1.3 you can use multiple namespaces on your events, like so:

$('.class').bind('click.a.b', function(){}); 
$('.class').trigger('click.a');
$('.class').unbind('click.b');