javascriptsafaridom-eventsanonymous-function

removeEventListener on anonymous functions in JavaScript


I have an object that has methods in it. These methods are put into the object inside an anonymous function. It looks like this:

var t = {};
window.document.addEventListener("keydown", function(e) {
    t.scroll = function(x, y) {
        window.scrollBy(x, y);
    };
    t.scrollTo = function(x, y) {
        window.scrollTo(x, y);
    };
});  

(there is a lot more code, but this is enough to show the problem)

Now I want to stop the event listener in some cases. Therefore I am trying to do a removeEventListener but I can't figure out how to do this. I have read in other questions that it is not possible to call removeEventListener on anonymous functions, but is this also the case in this situation?

I have a method in t created inside the anonymous function and therefore I thought it was possible. Looks like this:

t.disable = function() {
    window.document.removeEventListener("keydown", this, false);
}

Why can't I do this?

Is there any other (good) way to do this?

Bonus info; this only has to work in Safari, hence the missing IE support.


Solution

  • I believe that is the point of an anonymous function, it lacks a name or a way to reference it.

    If I were you I would just create a named function, or put it in a variable so you have a reference to it.

    var t = {};
    var handler = function(e) {
        t.scroll = function(x, y) {
            window.scrollBy(x, y);
        };
        t.scrollTo = function(x, y) {
            window.scrollTo(x, y);
        };
    };
    window.document.addEventListener("keydown", handler);
    

    You can then remove it by

    window.document.removeEventListener("keydown", handler);