jQuery: event namespaces

In jQuery, event namespaces are related to a particular feature of the bind() and unbind() methods. These methods accept a period-separated list of event namespaces attached to the main event name. Without namespaces, you're forced to remove a given event handler in this way:

$(element).unbind('click', handler);

Instead, you can use event namespaces as follows:

$(element).bind('click.myEvent', handler);
$(element).unbind('click.myEvent');

Using namespaces, you're not forced to refer directly the handler passed to these methods, but only its namespace. You can remove multiple handlers with namespace as once:

$(element).unbind('click.myEvent.anotherEvent');

The syntax used here is much similar to the syntax used for CSS classes. You can even remove a namespace handler without specifying the type of event you're using:

$(element).unbind('.myEvent');

In this case, the handler is removed regardless of the event type.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.