I have an EventListener that listens to the entire document and records keystrokes, but I want to remove this Listener when certain conditions are met.
The following is a snippet of my code:
document.addEventListener('keyup', function(e) {
var letter_entered = String.fromCharCode(e.keyCode).toLowerCase();
player.makeGuess(letter_entered);
if(player.win_status === true || player.lose_status === true) {
document.removeEventListener('keyup', arguments.callee, false);
}
});
This works, however according to the Mozilla Developer Docs this method has been deprecated.
I'm aware that I can simply name the function, but is there an alternative that would allow me to continue using the unnamed function?
Use the following process:
Use it as such:
var foo = function(e)
{
"use strict";
console.log(e);
document.removeEventListener('keyup', foo, false);
}
document.addEventListener('keyup', foo);
You can solve this problem easily using the y
combinator:
function y(f) {
return function () {
return f.bind(null, y(f)).apply(this, arguments);
};
}
Now you can rewrite your code as follows:
document.addEventListener("keyup", y(function (callee, e) {
player.makeGuess(String.fromCharCode(e.keyCode).toLowerCase());
if (player.win_status || player.lose_status) document
.removeEventListener("keyup", callee);
}));
That's all folks.
Use another anonymous function as a wrapper to store a named function (callee shim) to your original function:
document.addEventListener('keyup', (function(e)
{
var aFunction = function()
{
var letter_entered = String.fromCharCode(e.keyCode).toLowerCase();
player.makeGuess(letter_entered);
};
if(player.win_status === true || player.lose_status === true)
{
document.removeEventListener('keyup', window, false);
}
else
{
aFunction();
}
}
), false);
References
Strict Mode is Coming to Town
ES3.1:arguments.callee
Recursion with anonymous (inline) functions in XPath 3.0
Recursion with anonymous (inline) functions in XPath 3.0, Part II
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With