如何将自定义参数传递给事件处理程序

How to Pass Custom Parameters to Event Handler

本文关键字:事件处理 程序 参数传递 自定义      更新时间:2023-09-26

刚刚开始使用Dojo。我想传递几个自定义参数到事件处理程序。在jQuery中,你可以这样做:

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

customData可以像这样从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。局部/dojo。为您创建闭包。

function event_handler(customData, evt){
     ///
}
dojo.connect(node, 'onclick', dojo.partial(event_handler, 17))

请注意,所有这些都需要在创建事件处理程序时记住传递额外的参数。我不知道你是否可以做一个更直接的JQuery代码翻译,因为这将需要额外的evt变量的消息,我不认为dojo做这个

Also:

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){...}