Trigger Custom Events with jQuery

Author : Scott Lewis

Tags : jQuery, Javascript

Things have come a long way since the early days of the web and standard JavaScript window.onload and element.onclick event handling. Even using JavaScript on your web page was risky business in the early days because the availability and acceptance of JavaScript was so unpredictable.

JavaScript frameworks and libraries like jQuery have brought a level of ease and sophistication to web applications that is hard to overstate. One of the truly wonderful features of jQuery is the ability to respond to any user event by binding event handlers to just about anything – event custom events that you define.

This JavaScript magic is accomplished using the jQuery.bind() and jQuery.trigger() methods. The jQuery.bind() method attaches a bit of code to an event which will be executed later when jQuery.trigger() is called on that event.

jQuery.bind() – A Closer Look

There three ways to bind callbacks to events in jQuery. The first uses the standard jQuery.bind() method:

$("#some-element").bind("click", function(/* jQuery.Event */ event) {
    doSomethingKickAss(event);
});

jQuery also provides a shorthand method for the most common events:

$("#some-element").click(function(event) {
    doSomethingKickAss(event);
});

In jQuery parlance, this is the same as doing the following in traditional, vanilla JavaScript:

document.getElementById("some-element").onclick = function(event) {
    event = event || window.event;
    doSomethingKickAss(event);
};

The function that you attach to the event is referred to as a callback or event handler. An instance of a jQuery.Event object is passed to the function as the first argument by default.

$("#some-element").bind("click", function(event) {
    doSomethingKickAss(event);
});

The jQuery example above is probably familiar to you but there is a lot more you can do with jQuery.bind().

Binding Event Handlers to Multiple Events You can attach a callback to multiple events at once by providing the event names as space-separated items:

$("#some-element").bind("mouseenter mouseleave", function(event) {
    doSomeKickAssHovering(event);
});

Or you can pass your events and callbacks as a JavaScript object:

$("#some-element").bind({
    "mouseenter": function(/* jQuery.Event */ event) {
        // Do something kick-ass
    },
    "mouseleave": function(/* jQuery.Event */ event) {
        // Do something else kick-ass
    },
    "click": function(/* jQuery.Event */ event) {
        // Do something even more kick-ass
    }
});

Custom jQuery Events

In addition to the standard DOM Events such as click, mouseenter and mouseleave, jQuery allows you to attach callbacks to custom events on elements. Let’s give our custom event the very creative name of main_event. We can bind a callback to the event with the code below. Take note of the second parameter called params. It will be explained shortly.

$("#some-element").bind("main_event", function(event, params) {
    doSomethingKickAss(params);
});

Now at some later point in our code, we can trigger the event thus:

$("#some-element").trigger("main_event", "Known at execution time");

Another thing to note about custom events is that they do not have to be attached to a DOM element. Events can be attached to any object. For instance, if you create a custom JavaScript object, you can bind callbacks to custom events to the object.

if (typeof(MyObject) === "undefined") MyObject = {};
 
/**
 * Bind a callback to a custom event on MyObject
 */
$(MyObject).bind("main", function(event, theData) {
    alert(theData);
});
 
/**
 * Now trigger the custom event on the custom object
 */
$(MyObject).trigger("main", "Welcome to the main event");

The technique above becomes especially useful when you are creating a heavy-weight, custom application with jQuery such as the WYMeditor HTML Editor. I will explore this technique in detail in an upcoming post on pluggable jQuery applications.

Passing Data to Event Handlers in jQuery

There are two ways to pass data to an event handler: at the time the event handler is bound or at the time the event handler is triggered. Let’s tackle the second method first.

Notice the second argument in the previous example – the string that read Some data known at execution time. When jQuery executes the callback that was attached to #some-element, the string will be passed in the params parameter. The parameter can contain any data type you need it to: a string, an array, an object or any other JavaScript data type.

You can also pass data to the event handler when it is bound to an event by passing the data as part of the jQuery.Event object. You do it like this:

var theData = "Known before execution time";
$("#some-element").bind("click", theData, function(event) {
    doSomethingKickAss(event.data);
});

Notice that the data is passed as the second parameter of the jQuery.bind() method. Also notice that you access the passed data via the jQuery.Event.data property.

In this article, I have explained how to use jQuery.bind() and jQuery.trigger(). Using custom events and these two methods in jQuery allows you to build sophisticated rich applications that can respond to users’ actions in a very fine-tuned manner. In the next post, I will demonstrate a real-world use of custom events and explain their use can help improve code management.

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.