Namespaced Events with jQuery

Author : Scott Lewis

Tags : jQuery, Javascript

A few days ago in a post titled Trigger Custom Events in jQuery, I demonstrated how to work with jQuery.bind() and jQuery.trigger() to create and execute custom events. This article will explore jQuery events a bit more by taking a look at namespaced events.

In addition to allowing you to define custom events to which you can attach event handlers, jQuery allows you to namespace events, including standard events like click and mouseover. At first glance this fact may not seem all that interesting but with a little exploration it will become clear that this is a very useful feature.

Let’s say, for instance, that you want an event handler to be triggered only once. Without namespaces, how else would you prevent the event handler from being triggered each time the event occurs? If you simply call jQuery.unbind(eventname), then all the event handlers will be removed. The ability to namespace events, however, allows you to remove only some event handlers while leaving other intact.

Example Code

To add a namespace to an event, simply add a class name in the manner demonstrated in the code below by the .run_once namespace on the first click event.

$(function() {
 
    var testData1 = "This is click.run_once";
 
    $("button").bind("click.run_once", testData1, function(e) {
        alert(e.data);
        $("button").unbind("click.run_once");
    });
 
    var testData2 = "This is click";
 
    $("button").bind("click", testData2, function(e) {
        alert(e.data);
    });
 
});

jQuery also allows you to add multiple namespaces to an event:

$(function() {
 
    $("button").bind("myevent.namespace1.namespace2", function(e) {
        alert(e.namespace);
    });
 
    $("button").bind("click", function(e) {
        $("button").trigger("myevent.namespace1");
        $("button").trigger("myevent.namespace2");
    });
});

jQuery allows you, the web application developer, to write very rich applications to respond to user behavior. Custom events and namespaced events give you fine-grained control over the user interface and allow you to tailor application behaviors in unlimited combinations.

Posted in JavaScript | Tag: jQuery, Javascript

Pay it forward

If you find value in the work on this blog, please consider paying it forward and donating to one of the followign charities that are close to my heart.