itsmikem itsmikem - 7 months ago 5
Javascript Question

jquery .on() with multiple events AND passing arbitrary data

I know you can pass multiple events to

.on()
like so:

$(".myThing").on({
mousedown:mouseDownFunction,
mouseup:mouseUpFunction
});


...and I know you can pass arbitrary data along with
.on()
, like so:

$(".myThing").on("click",{myParam:5},clickFunction);


But is there syntax to define multiple events while also passing arbitrary data? I'm not seeing how to do that in the docs.

Answer

You can pass data as the second optional parameter:

$(".myThing").on({
     mousedown: mouseDownFunction,
     mouseup: mouseUpFunction
}, {myParam: 5});

Then inside of the event handlers you will be able to access this data as e.data.myParam, where e is a parameter (instance of an event object) of the invoked event handler function.