Javascript插件语法:如何正确地将匿名函数传递给事件监听器?

时间:2017-08-30 19:46:54

标签: javascript jquery

编辑:我做了一些更改,以重新澄清我遇到的问题。

我有一个简单的Javascript插件,我想添加一些回调功能作为其默认功能的一部分。用户可以指定在单击某个按钮时要调用的函数。

// Define option defaults
var defaults = {
  //some other defaults
  onOK: null, //callback functions to be specified here (exists as string)
  onClose: null //callback functions to be specified here (exists as string)
}

通常情况下,当没有参数的简单函数时,这样可以正常工作。该选项传递到此处:

function initializeEvents() {
    //If a close button event is clicked, run this.
    if (this.closeButton) {
      this.closeButton.addEventListener('click', this.close.bind(this)); //Bind close event to the button
      this.closeButton.addEventListener('click', window[this.options.onClose]); //passed to here
    }
    //If an OK button event is clicked, run this.
    if (this.okButton) {
      this.okButton.addEventListener('click', this.close.bind(this));
      this.okButton.addEventListener('click', window[this.options.onOK]); //passed to here
    }
  }

window[]应该成为对相应按钮的函数调用。 我注意到我不应该使用window[]

编辑:然而,正如@adeneo指出的那样,我在这里通过将我的函数添加为字符串来犯这个大错误,这只会导致函数变为undefined而不是我必须将其添加到事件监听器。

我尝试过使用匿名功能,但我还没有让这个功能起作用:

var callbackModal = new raModal({
            content: '<div>You clicked on the Callback button. This shows the popup, but has a custom callback function, called when the user clicks OK and/or Close.</div>',
            onOK:{function(){
                    okCallback('4');
                 }
            },
            onClose: "closeCallback",
            closeButtonText: "Close"
        });
        callbackModal.open();

所以,我的问题已改为: 如何从默认设置中正确添加我的匿名函数?

Link to a JSFiddle that reproduces the issue.您会注意到,当“关闭”按钮按预期工作时(closeCallback打印console.log消息),调用okCallback(num)的“确定”按钮不执行任何操作。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您可以将参数传递给JavaScript函数,而无需在函数签名上使用参数名称。这应该是解决您问题的方法。

请参阅Is it possible to get all arguments of a function as single object inside that function?

答案 1 :(得分:0)

使用有风险的initializeEvents()实现,不是尝试将回调绑定到window[]中的按钮,而是在按钮对象构造完成后简单地将它们附加到它们之后。

我做了两个额外的函数来为OK和Close按钮添加事件监听器:

  function closeCallback(callback){
    $(".ra-close").click(callback);
  }
  function okCallback(callback){
    $(".ra-ok").click(callback);
  }

buildOut()函数内部,完成所有操作后,使用我们的自定义选项作为参数添加对事件侦听器的调用,现在可以是匿名函数!

closeCallback(this.options.onClose);
okCallback(this.options.onOK);

还有一个额外的实用程序功能,可以将用户选项扩展到新模式,但没有正确跟踪null值。我删除了if语句,检查了这些语句,看到我们将它们作为defaults变量的一部分。

  // Utility method to extend defaults with user options
  function extendDefaults(source, properties) {
    var property;
    for (property in properties) {
        source[property] = properties[property];
    }
    return source;
  }

Here's the updated JSFiddle with the corrected plugin code.

相关问题