首页 > 解决方案 > JavaScript:如何将参数传递给最终将被删除的侦听器函数

问题描述

我正在尝试调用一个函数,该函数具有触发事件时所依赖的参数。但是,此函数不能是匿名的,因为将来会删除侦听器。

我尝试对包装器使用函数表达式,并this在主函数中将引用作为参数传递:

<div id="div">
  click
</div>
function main() {
  let foo = "foo";
  let bar = "bar";
  let wrapFunction = function(event) {
    goodFunction(event, foo, bar, this);
  }
  document.getElementById("div").addEventListener("click", wrapFunction);
}
function goodFunction(e, foo, bar, wrapFunction) {
  alert(foo);
  alert(bar);
  document.getElementById("div").removeEventListener("click", wrapFunction);
}
main();

一切正常,除了document.getElementById("div").removeEventListener("click", wrapFunction);线路。这是我无法弄清楚的部分,我们将不胜感激。

标签: javascriptaddeventlistenerremoveeventlistener

解决方案


而不是传递thisgoodFunction(event, foo, bar, this)内部的调用wrapFunction,您可以只传递wrapFunction自己,看到它是由调用处理程序的时间定义的:

function main() {
  let foo = "foo";
  let bar = "bar";
  let wrapFunction = function(event) {

    /* wrapFunction is defined so pass it directly to goodFunction */
    goodFunction(event, foo, bar, wrapFunction);
  }
  document.getElementById("div").addEventListener("click", wrapFunction);
}

function goodFunction(e, foo, bar, wrapFunction) {
  alert(foo);
  alert(bar);
  document.getElementById("div").removeEventListener("click", wrapFunction);
}
main();
<div id="div">Click me</div>


推荐阅读