javascript 如何将自定义参数传递给事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6893055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Pass Custom Parameters to Event Handler
提问by Jonah
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:
刚开始使用 Dojo。我想将几个自定义参数传递给事件处理程序。在 jQuery 中,你可以这样做:
$('#button').click({
customData: 'foo'
}, handlerFunction);
And customData
can be accessed from handlerFunction
like this:
并且customData
可以handlerFunction
像这样访问:
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?
我正在将一些 jQuery 代码迁移到 Dojo。如何将这些参数传递给 Dojo 事件处理程序?
回答by hugomg
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 中连接事件时:
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.
我非常喜欢的另一种可能性是使用 dojo.partial / dojo.hitch 为您创建闭包。
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.
请注意,所有这些都需要在创建事件处理程序时考虑传递额外的参数。我不知道您是否可以对 JQuery 代码进行更直接的翻译,因为这需要对 evt 变量进行额外的按摩,而且我认为 dojo 不会这样做。
回答by DLeonardi
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){...}