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?
我在t中创建了一个方法在匿名函数内,因此我认为这是可能的。看起来像这样:
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中工作,因此缺少即支持。
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屋!