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

6

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

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

并且通过以下方式可以在 handlerFunction 中访问 customData

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

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

2个回答

12

通常情况下,闭包允许您向函数传递“隐藏”的参数:

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不会这样做。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接