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 handlerF开发者_StackOverflowunction
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?
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.
Also:
this.connect(other, "onClick", function(e) {
/* other is accesible here still */
});
or :
this.connect(other, "onClick", dojo.hitch(this, "handler", other);
and its event handler:
this.handler = function(other, evt){...}
精彩评论