Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

Namespaces

As you've already learned, when we want to create our own event handler, we write code like this:

// create our handler
$("p").on("click", function() {
    // do something
    alert("Click!");
});

When we need to remove handlers, we use:

// remove all handlers
$("p").off();

// remove all click handlers
$("p").off("click");

But, as always, there are situations when we need to enable or disable not all handlers (for example, we need to disable a specific plugin's handling of some control). That's where namespaces come to the rescue, and they're pretty easy to use.

When creating an event handler, add a namespace with a dot:

// create a handler
$("p").on("click.namespace", function(event){
    // do something
    alert("Click: " + event.namespace + "!");
});

When we need to trigger only the handler bound to our namespace, we use the following syntax:

When we trigger an event from a different namespace, our handler won't be called:

When we trigger all event handlers:

When we trigger all handlers without a namespace:

Before version 1.9, you would use an exclamation mark with the event name click! for this purpose, and after — this workaround exploiting a quirk in a regular expression.

And the last case — removing an event handler bound to our "namespace":

You can even remove all handlers from a specific namespace in one shot:

Here's another useful example of a crafty handler — it can catch and process data:

Trigger the event, passing an array of arguments as data:

I also wanted to draw attention to the support for multiple namespaces:

The official documentation is scarce on this topic, and I hope my examples helped you understand it better. And here's one more comprehensive example of working with namespace:

Last updated