情况有点像

var someVar = some_other_function();
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);

问题是someVar的值在addEventListener的侦听器函数中是不可见的,在addEventListener中它可能被视为一个新变量。


当前回答

如果以后想要删除事件侦听器,那么创建对curry函数的引用是一个不错的选择。

在下面的代码中,我将说明我的意思。

// This is the curry function. We return a new function with the signature of what the click-listener expects
const handleClick = (foo, bar) => (clickEvent) => {
  console.log('we get our custom input', foo, bar);
  console.log('we get the click event too', clickEvent);
}

// We need to store a reference to the listener, making sure we are removing the correct reference later
const myListener = handleClick('foo', 'bar'); // Remember that we now return the actual event-handler


const btn = document.getElementById('btn'); // find the element to attach the listener to
btn.addEventListener('click', myListener);

// remove the event listener like this by using our reference
btn.removeEventListener('click', myListener);

下面是CodePen上的一个工作示例

其他回答

您可以通过将函数声明为变量来添加和删除带有参数的事件侦听器。

myaudio.addEventListener(’ended’、funcName =功能(false) (newSrc myaudio)});

newSrc是以myaudio为参数的方法 funcName是函数名变量

可以使用删除侦听器 myaudio.removeEventListener(“结束”,func假);

你可以用'bind'绑定所有必要的参数:

root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));

通过这种方式,您将始终获得事件、arg1和其他传递给myPrettyHandler的东西。

http://passy.svbtle.com/partial-application-in-javascript-using-bind

    $form.addEventListener('submit', save.bind(null, data, keyword, $name.value, myStemComment));
    function save(data, keyword, name, comment, event) {

这就是我如何正确地传递事件。

我的方法非常简单。这可能对其他人有用,就像它帮助了我一样。 它是…… 当你有多个元素/变量分配给同一个函数,你想要传递引用,最简单的解决方案是…

function Name()
{

this.methodName = "Value"

}

就是这样。 这对我很管用。 那么简单。

可能不是最优的,但对于那些不精通js的人来说已经足够简单了。将调用addEventListener的函数放到它自己的函数中。通过这种方式,传递给它的任何函数值都保持自己的作用域,并且您可以尽可能多地迭代该函数。

示例我与文件读取,因为我需要捕捉和渲染图像和文件名的预览。在使用多文件上传类型时,我花了一段时间来避免异步问题。尽管上传了不同的文件,我还是会意外地在所有渲染中看到相同的“名称”。

最初,所有的readFile()函数都在readFiles()函数中。这导致了异步作用域问题。

    function readFiles(input) {
      if (input.files) {
        for(i=0;i<input.files.length;i++) {

          var filename = input.files[i].name;

          if ( /\.(jpe?g|jpg|png|gif|svg|bmp)$/i.test(filename) ) {
            readFile(input.files[i],filename);
          }
       }
      }
    } //end readFiles



    function readFile(file,filename) {
            var reader = new FileReader();

            reader.addEventListener("load", function() { alert(filename);}, false);

            reader.readAsDataURL(file);

    } //end readFile