Tuesday, October 13, 2009

jQuery Custom Events

One of the more powerful features of the jQuery javascript toolkit is the ability to create custom event types. In addition to the built-in events that are triggered by standard DOM elements, developers have the ability to create custom events. These events that are defined by developers using jQuery are not all that different from the standard DOM events. The main difference being that the developers can have control over the event data and when they are triggered.

The custom jQuery events can be created using the jQuery.Event() function. The one required parameter of this function is the event name. The instance of the custom event is returned. Another parameter that might be passed to the function is an object that contains the event data. However, an event instance created by jQuery.Event() can also have attributes set on it directly. Either way, these values will be passed along with the event once it has been triggered.

Event driven programming is a very useful model. Especially when the application is user interface centric. Here, the application consists almost exclusively of events. The user does something, some event is fired and some handler acts accordingly. With javascript applications, there is also the prospect of triggering events when data arrives from some API request. In fact, without an event to notify the application that the data has arrived, the application would be considered synchronous and would not respond well to user interaction.

Custom javascript events created by developers can be broadcast across the entire application or sent as a signal to a specific DOM element. The more useful method is to broadcast the event because it allows any application component to subscribe to the event. This offers flexibility and reduces the amount of code needed to accomplish a specific task.