説明が必要なremoveEventListener()で問題が発生しました。
イベントリスナーにパラメーターを渡せるようにしたかったので、イベントリスナーを生成する関数を作成しました。この関数は、目的のイベントリスナーをコールバックとして呼び出す2番目の関数を返します。
完全なライブラリファイルは次のとおりです。
//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]クリックイベントハンドラーをボタン#1にアタッチします。
[2]ボタンをクリックしたときにイベントハンドラーが呼び出されるかどうかをテストします。
[3]そのテストに合格したら、ボタン#2をクリックし、それに接続されているイベントハンドラーを呼び出します。これにより、ボタン#1に接続されている古いイベントハンドラーが削除され、新しいイベントハンドラーに置き換えられます。
手順[1]と[2]は正常に機能します。イベントハンドラーがアタッチされており、ボタンをクリックするたびに呼び出されます。
問題はステップ[3]にあります。
特にステップ[3]でそのイベントリスナーを削除する目的で、MakeEventHandler()によって生成された関数への参照を保存しましたが、removeEventListener()を呼び出してもイベントリスナーは削除されません。続いてボタン#1をクリックすると、削除したと思われるものを含め、両方のイベントリスナーが起動します。
言うまでもなく、removeEventListener()の呼び出しで指定する関数が、addEventListener()で最初に追加した関数と同じになるようにすべてを注意深く設定しているにもかかわらず、この動作は不可解です。 (このスレッドを含めて)読んだことがあるので、呼び出しごとに同じ関数への参照を渡すことは機能するはずですが、明らかに機能しません。
ステップ[1]で、コンソールのテスト出力は期待どおりに読み取られます。
ボタン1の初期イベントハンドラーがトリガーされました
コードも期待どおりにステップ[2]で実行され、コードのステップバイステップのトレースにより、実際にコードが期待どおりに実行されていることがわかります。
ただし、ステップ[3]では、ボタン#1を最初にクリックすると、目的の結果が得られます。
ボタン1の最終イベントハンドラーがトリガーされました
続いてボタン#1をクリックすると、次のようになります。
ボタン1の初期イベントハンドラーがトリガーされましたボタン1の最終イベントハンドラーがトリガーされました
確かに、ボタン#1に最初にアタッチされた関数がまだメモリに残っている場合でも、クロージャー内で生成されたため、要素のイベントリスナーコレクションからデタッチする必要がありますか?なぜまだ接続されているのですか?
または、イベントリスナーでクロージャを使用することに関する奇妙なバグに遭遇しましたが、それを報告する必要がありますか?