我遇到了需要解释的 removeEventListener() 问题。
我希望能够将参数传递给事件侦听器,因此我编写了一个函数来生成事件侦听器,该函数又返回第二个函数,该函数将我想要的事件侦听器作为回调调用。
完整的库文件如下:
//Event handler constants
function EventHandlerConstants()
{
this.SUCCESS = 0; //Signals success of an event handler function
this.NOTFUNCTION = 1; //actualHandler argument passed to MakeEventHandler() is not a Function object
//End constructor
}
//MakeEventHandler()
//Arguments:
//actualHandler : reference to the actual function to be called as the true event handler
//selfObject : reference to whatever object is intended to be referenced via the "this" keyword within
// the true event handler. Set to NULL if no such object is needed by your true
// event handler specified in the actualHandler argument above.
//args : array containing the arguments to be passed to the true event handler, so that the true
// event handler can be written with named arguments, such as:
// myEventHandler(event, arg1, arg2, ... )
// If your function doesn't need any arguments, pass an empty array, namely [], as the
// value of this argument.
//Usage:
//c = new EventHandlerConstants();
//res = MakeEventHandler(actualHandler, selfObject, args);
//if (res == c.SUCCESS)
// element.addEventListener(eventType, res.actualHandler, true); //or whatever
function MakeEventHandler(actualHandler, selfObject, args)
{
var c = new EventHandlerConstants();
var funcReturn = null; //This will contain a reference to the actual function generated and passed back to
//the caller
var res = {
"status" : c.SUCCESS,
"actualHandler" : null
};
if (IsGenuineObject(actualHandler, Function))
{
res.actualHandler = function(event) {
var trueArgs = [event].concat(args);
actualHandler.apply(selfObject, trueArgs);
};
}
else
{
res.status = c.NOTFUNCTION;
//End if/else
}
//Return our result object with appropriate properties set ...
return(res);
//End function
}
然后我写了一个快速测试页面来确定这是否按预期工作,并允许我随意添加和删除事件处理程序。
HTML测试页面如下:
<!DOCTYPE html>
<html>
<head>
<!-- CSS goes here -->
<link rel="stylesheet" type="text/css" href="NewEventTest.css">
<!-- Required JavaScript library files -->
<script language = "JavaScript" src="BasicSupport.js"></script>
<script language = "JavaScript" src="EventHandler6.js"></script>
</head>
<body class="StdC" id="MainApplication">
<button type="button" class="StdC NoSwipe" id="Button1">Try Me Out</button>
<button type="button" class="StdC NoSwipe" id="Button2">Alter The 1st Button</button>
</body>
<script language = "JavaScript" src="NewEventTest.js"></script>
</html>
为了完整起见,我也使用以下简单的 CSS 文件:
/* NewEventTest.css */
/* Define standard display settings classes for a range of HTML elements */
.StdC {
color: rgba(255, 255, 255, 1);
background-color: rgba(0, 128, 0, 1);
font-family: "Book Antiqua", "Times New Roman", "Times", serif;
font-size: 100%;
font-weight: normal;
text-align: center;
}
.NoSwipe {
user-select: none; /* Stops text from being selectable! */
}
测试代码如下:
//NewEventTest.js
function GlobalVariables()
{
this.TmpRef1 = null;
this.TmpRef2 = null;
this.TmpRef3 = null;
this.Const1 = null;
this.Handler1 = null;
this.Handler2 = null;
this.Handler3 = null;
this.EventOptions = {"passive" : true, "capture" : true };
//End constructor
}
//Button 1 Initial function
function Button1Initial(event)
{
console.log("Button 1 initial event handler triggered");
//End event handler
}
function Button1Final(event)
{
console.log("Button 1 final event handler triggered");
//End event handler
}
function Button2Handler(event, oldFunc, newFunc)
{
var funcRef = null;
this.removeEventListener("click", oldFunc);
this.addEventListener("click", newFunc, GLOBALS.EventOptions);
//End event handler
}
//Application Setup
GLOBALS = new GlobalVariables();
GLOBALS.Const1 = new EventHandlerConstants();
GLOBALS.TmpRef1 = document.getElementById("Button1");
GLOBALS.TmpRef2 = MakeEventHandler(Button1Initial, null, []);
if (GLOBALS.TmpRef2.status == GLOBALS.Const1.SUCCESS)
{
GLOBALS.Handler1 = GLOBALS.TmpRef2.actualHandler;
GLOBALS.TmpRef1.addEventListener("click", GLOBALS.Handler1, GLOBALS.EventOptions);
//End if
}
GLOBALS.TmpRef1 = MakeEventHandler(Button1Final, null, []);
if (GLOBALS.TmpRef1.status == GLOBALS.Const1.SUCCESS)
{
GLOBALS.Handler3 = GLOBALS.TmpRef1.actualHandler;
//End if
}
GLOBALS.TmpRef1 = document.getElementById("Button2");
GLOBALS.TmpRef2 = document.getElementById("Button1");
GLOBALS.TmpRef3 = Button1Final;
GLOBALS.TmpRef4 = MakeEventHandler(Button2Handler, GLOBALS.TmpRef2, [GLOBALS.Handler1, GLOBALS.Handler3]);
if (GLOBALS.TmpRef4.status == GLOBALS.Const1.SUCCESS)
{
GLOBALS.Handler2 = GLOBALS.TmpRef4.actualHandler;
GLOBALS.TmpRef1.addEventListener("click", GLOBALS.Handler2, GLOBALS.EventOptions);
//End if
}
因此,要执行的测试如下:
[1] 将点击事件处理程序附加到 Button #1;
[2] 测试我点击按钮时是否调用了事件处理程序;
[3] 一旦测试通过,点击 Button #2,并调用附加到其上的事件处理程序,这将删除附加到 Button #1 的旧事件处理程序,然后用新的事件处理程序替换它。
步骤 [1] 和 [2] 工作正常。事件处理程序已附加,并在我单击按钮时调用。
问题在于步骤 [3]。
即使我保存了对 MakeEventHandler() 生成的函数的引用,特别是为了在步骤 [3] 中删除该事件侦听器,对 removeEventListener() 的调用也不会删除事件侦听器。随后单击按钮 #1 会触发两个事件侦听器,包括我应该删除的那个!
不用说,尽管仔细设置了所有内容,以便我在 removeEventListener() 调用中指定的函数与我最初使用 addEventListener() 添加的函数相同,但我还是觉得这种行为令人费解——根据我关于该主题的所有文档'已经阅读(包括这个线程),为每个调用传递对相同函数的引用应该可以工作,但显然不行。
在步骤 [1] 中,控制台中的测试输出按预期读取:
按钮 1 初始事件处理程序已触发
正如预期的那样,代码也在步骤 [2] 中运行,并且对代码的逐步跟踪表明,确实,代码按预期执行。
但是在步骤 [3] 中,虽然第一次单击按钮 #1 会产生所需的结果:
按钮 1 最终事件处理程序已触发
随后单击 Button #1 时发生的情况是:
触发按钮 1 初始事件处理程序 触发按钮 1 最终事件处理程序
当然,即使最初附加到 Button #1 的函数仍然存在于内存中,因为它是在闭包中生成的,它仍然应该从元素的事件侦听器集合中分离出来吗?为什么还连接着?
还是我遇到了一些奇怪的错误,涉及使用带有事件侦听器的闭包,需要报告?