Search code examples
javascriptdojodom-events

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?


Solution

  • 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.