【问题标题】:How to Pass Custom Parameters to Event Handler如何将自定义参数传递给事件处理程序
【发布时间】:2011-07-31 23:35:28
【问题描述】:

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

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

customData 可以像这样从handlerFunction 访问:

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

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

【问题讨论】:

    标签: javascript dojo dom-events


    【解决方案1】:

    嗯,一般来说,闭包允许您将“隐藏”参数传递给函数:

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

    【讨论】:

    • 啊哈,dojo.partial 正是我要找的。谢谢!
    【解决方案2】:

    还有:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-02
      • 1970-01-01
      • 2022-01-13
      • 2012-08-30
      • 2018-12-05
      • 1970-01-01
      相关资源
      最近更新 更多