JavaScript 中匿名函数的 removeEventListener [英] 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)
现在我想在某些情况下停止事件侦听器.因此,我正在尝试执行 removeEventListener,但我不知道如何执行此操作.我在其他问题中读到,无法对匿名函数调用 removeEventListener,但在这种情况下也是如此吗?
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);
}
为什么我不能这样做?
有没有其他(好的)方法可以做到这一点?
Is there any other (good) way to do this?
奖金信息;这只需要在 Safari 中工作,因此缺少 IE 支持.
Bonus info; this only has to work in Safari, hence the missing IE support.
推荐答案
我相信这是匿名函数的重点,它缺少名称或引用它的方法.
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);
然后您可以删除它
window.document.removeEventListener("keydown", handler);
这篇关于JavaScript 中匿名函数的 removeEventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!