Passing data to jQuery events with event.data and custom $.Event object

Whenever handling an event in jQuery, be it a UI event or a programmatic event, it is very often required to pass some piece of data to it. It is common for novice developers to pull that data directly from globally scoped objects – variables or global DOM selectors – which is not the best practice, and with more sophisticated dynamic UIs it easily gets out of hand and becomes impossible to maintain in the longer run.

To avoid such issues, jQuery provides two easy mechanisms for passing data to event handlers. More after the jump.

Event.data

jQuery .bind() accepts a data map, which is then passed to the event method when the executing handler is bound. This is a nice and neat way to keep the event function locally scoped, instead of having it retrieve global variables or run some logic based on DOM selectors. The data map is then exposed as a “data” property of the $.Event object.

$.Event.data can contain any valid Javascript data type: string, array, or any custom or built-in object. Note that the same applies to all shortcut event handlers, such as .click() etc, as they simply extend .bind().

Custom Event Object

Whenever an event is to be raised programmatically (using .trigger()) another clean approach exists. Consider the following code sample:

In this case, clicking on the first button, actually triggers, programmatically, a click on the second button. In this case, we pass a custom Event object to .trigger(). Note the type property – that’s the one indicating the kind of event being raised.
In fact, such passing of an object literal to trigger(), is just a shortcut way of insantiating a $.Event. So this

could be written like this

To summarize, whenever you can avoid spaghettifying your code by mixing up local and global variables and DOM selectors in Javascript, you should do it. Event handling with passed data maps is a very useful technique to keep you front end code a clean and tidy.