2011-07-31 78 views
6

刚刚开始使用Dojo。我想将一些自定义参数传递给事件处理程序。在jQuery中,你可以做这样的:Dojo:如何将自定义参数传递给事件处理程序

$('#button').click({ 
    customData: 'foo' 
}, handlerFunction); 

而且customData可以从handlerFunction这样访问:

function handlerFunction(event) { 
    console.log(event.data.customData); 
} 

我迁移一点jQuery代码到道场。我如何将这些参数传递给Dojo事件处理程序?

回答

12

好,generaly,关闭允许您通过“隐藏”参数的函数:在道场连接的事件时

function make_event_handler(customData){ 
    return function(evt){ 
     //customData can be used here 
     //just like any other normal variable 
     console.log(customData); 
    } 
} 

所以:

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)) 

注意,所有这些这些必需的事件处理与传递额外的参数(S)记创建。我不知道你是否可以更直接地翻译JQuery代码,因为这需要对evt变量进行额外的处理,我不认为dojo会这样做。

+1

啊哈,'dojo.partial'正是我要找的。谢谢! – Jonah

1

另外:

this.connect(other, "onClick", function(e) { 
    /* other is accesible here still */ 
}); 

或:

this.connect(other, "onClick", dojo.hitch(this, "handler", other); 

和事件处理程序:

this.handler = function(other, evt){...} 
相关问题