Javascript 如何将自定义参数传递给事件处理程序
刚刚开始使用Dojo。我想向事件处理程序传递几个自定义参数。在jQuery中,您可以这样做:Javascript 如何将自定义参数传递给事件处理程序,javascript,dojo,dom-events,Javascript,Dojo,Dom Events,刚刚开始使用Dojo。我想向事件处理程序传递几个自定义参数。在jQuery中,您可以这样做: $('#button').click({ customData: 'foo' }, handlerFunction); function handlerFunction(event) { console.log(event.data.customData); } 可以从handlerFunction访问customData,如下所示: $('#button').click({
$('#button').click({
customData: 'foo'
}, handlerFunction);
function handlerFunction(event) {
console.log(event.data.customData);
}
可以从handlerFunction
访问customData
,如下所示:
$('#button').click({
customData: 'foo'
}, handlerFunction);
function handlerFunction(event) {
console.log(event.data.customData);
}
我正在将一些jQuery代码迁移到Dojo。如何将这些参数传递给Dojo事件处理程序?通常,闭包允许您将“隐藏”参数传递给函数:
function make_event_handler(customData){
return function(evt){
//customData can be used here
//just like any other normal variable
console.log(customData);
}
}
因此,在dojo中连接事件时:
dojo.connect(node, 'onclick', make_event_handler(17));
我非常喜欢的另一种可能性是使用dojo.partial/dojo.hitch为您创建闭包
function event_handler(customData, evt){
///
}
dojo.connect(node, 'onclick', dojo.partial(event_handler, 17))
请注意,所有这些都需要在创建事件处理程序时考虑传递额外的参数。我不知道是否可以对JQuery代码进行更直接的翻译,因为这需要对evt变量进行额外的处理,我认为dojo不会这样做。另外:
this.connect(other, "onClick", function(e) {
/* other is accesible here still */
});
或:
及其事件处理程序:
this.handler = function(other, evt){...}
啊哈,
dojo.partial
正是我要找的。谢谢