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

Jon*_*nah 6 javascript dojo dom-events

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

$('#button').click({
    customData: 'foo'
}, handlerFunction);
Run Code Online (Sandbox Code Playgroud)

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

function handlerFunction(event) {
    console.log(event.data.customData);
}
Run Code Online (Sandbox Code Playgroud)

我正在将一些jQuery代码迁移到Dojo.如何将这些参数传递给Dojo事件处理程序?

hug*_*omg 12

好吧,通常,闭包允许您将"隐藏"参数传递给函数:

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

所以在dojo中连接事件时:

dojo.connect(node, 'onclick', make_event_handler(17));
Run Code Online (Sandbox Code Playgroud)

我喜欢的另一种可能性是使用dojo.partial/dojo.hitch为您创建闭包.

function event_handler(customData, evt){
     ///
}

dojo.connect(node, 'onclick', dojo.partial(event_handler, 17))
Run Code Online (Sandbox Code Playgroud)

请注意,所有这些都需要在创建事件处理程序的同时记住额外的参数.我不知道你是否可以更直接地翻译JQuery代码,因为这需要额外的evt变量按摩,我不认为dojo会这样做.