Just getting started with Dojo. I want to pass a couple of custom parameters to an event handler. In jQuery, you can do it like this:
$('#button').click({
customData: 'foo'
}, handlerFunction);
And customData
can be accessed from handlerFunction
like this:
function handlerFunction(event) {
console.log(event.data.customData);
}
I'm migrating a bit of jQuery code over to Dojo. How can I pass those parameters to the Dojo event handler?
If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.
Parameters of the even handlers are defined by the "event arguments" class (derived from System. EventArgs ); and you cannot change the signature of the event handler. So, you should have asked, "can I pass additional information?". Of course you can.
A\ rewrite the save method and include it in this class (yuk), B\ have an overloaded save option that takes an object as a parameter, so I can pass it through to my record class, and then merge it with the identity number.
EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information. Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event.
Well, generaly, closures allow you to pass "hidden" parameters to a function:
function make_event_handler(customData){
return function(evt){
//customData can be used here
//just like any other normal variable
console.log(customData);
}
}
So when connecting an event in dojo:
dojo.connect(node, 'onclick', make_event_handler(17));
Another possibility that I like a lot is using dojo.partial / dojo.hitch to create the closures for you.
function event_handler(customData, evt){
///
}
dojo.connect(node, 'onclick', dojo.partial(event_handler, 17))
Note that all of these these required your event handlers to be created with passing the extra parameter(s) in mind. I don't know if you can do a more direct translation of the JQuery code since that would require extra massaging of the evt variable and I don't think dojo does that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With