Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass Custom Parameters to Event Handler

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?

like image 823
Jonah Avatar asked Jul 31 '11 23:07

Jonah


People also ask

How do you pass parameters to an 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.

Is it possible to pass an additional parameter to an event handler?

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.

How do you pass a parameter to a callback function in C#?

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.

What is EventArgs EC?

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.


1 Answers

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.

like image 127
hugomg Avatar answered Sep 22 '22 10:09

hugomg