javascript - 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);
线路。这是我无法弄清楚的部分,我们将不胜感激。
解决方案
而不是传递this
给goodFunction(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>
推荐阅读
- javascript - 如何禁用/限制浏览器重新加载/刷新功能?
- javascript - 接受正数和负数的正则表达式
- swift - 如何在另一个模块中使用 Swift 扩展?
- minecraft - Minecraft 1.12.2 改装服务器:“出现问题”
- c# - 车把块助手未注册
- typescript - 为什么需要添加文本更改事件以及我们如何在 Aurelia 应用程序中添加
- if-statement - vars 在 rewrite_by_lua_block 后不起作用
- reactjs - 为什么即使我没有渲染任何东西,我也会收到“对象作为 React 孩子无效”的错误?
- javascript - 如何自动调整文本区域的大小以适应内容?
- java - 在数组中查找重复项,在 java 中填充重复次数最多的第二个数组