Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

javascript - Alternative to arguments.callee

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the following process:

  • Create a variable
  • Assign an anonymous function to the variable
  • Invoke it with the variable reference
  • The anonymous function references itself using the variable name

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...