jQuery Event Namespacing

by Staff Coder

on January 9, 2017

jQuery Event Namespacing

What is event handling? The majority of JavaScript code is triggered from an event. For example, an event fires when the page loads; press a key; click a button; or move your mouse. Event handling tells JavaScript what to do in these situations - how to handle the event that was fired.

In jQuery, you can easily and quickly add event handlers to add behaviour to your code:

$("#element")
  .on("click", doSomething)
  .on("click", doSomethingElse);

Just as easily, you can remove remove event listners:

$("#element")
  .off("click");

But wait, the code above will remove both handlers. What if we only need to remove just one?
For this, we would need a way to differentiate each .on(...) binding event using event namespace. Namespaced Events

So instead of just specifing click as the event handler, you use the click.name_space

$( "p" ).on( "click.doGood", function( event ) {
    console.log('You clicked doSomething');
});

$( "p" ).on( "click.doBetter", function( event ) {
    console.log('You clicked doSomethingElse');
});

Now that we have different bindings for the .on(...) events, we can use .off(...) to unbind just the one we need by specifying the exact event_name.

$( "p" ).off( "click.doBetter");

Event namespacing provides a way to manage specific event handlers at a granular level and without touching other bounded events.
Namespacing events in jQuery isn't limited to just .on(...) and .off(...) handlers. It also works with .bind() and .unbind() too.

Next: Using jQuery Event Triggers in your coding.