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

Β· 394 words Β· 2 minutes to read

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.

var data = {name:"Maple Leafs", sport: "hockey"};  
<input id="btn" type="button" />  
$("#btn").bind("click",data, function(e) {  
console.log(e.data.name + " " + e.data.sport);  
});  

$.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:

<input id="btn" type="button" />  
<input id="btn2" type="button" /> ​  
$("#btn").bind("click",function(e) {  
var data2 = {type:"click",name:"Raptors",sport:"basketball"};  
$("#btn2").trigger(data2);  
});  
$("#btn2").bind("click",function(e) {  
console.log(e.name + " " + e.sport);  
});  

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

var data2 = {type:"click",name:"Raptors",sport:"basketball"};  

could be written like this

var event = $.Event("click");  
event.name = "Raptors";  
event sport = "basketball";  

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.

About


Hi! I'm Filip W., a software architect from ZΓΌrich πŸ‡¨πŸ‡­. I like Toronto Maple Leafs πŸ‡¨πŸ‡¦, Rancid and quantum computing. Oh, and I love the Lowlands 🏴󠁧󠁒󠁳󠁣󠁴󠁿.

You can find me on Github, on Mastodon and on Bluesky.

My Introduction to Quantum Computing with Q# and QDK book
Microsoft MVP