Hammer.js无法删除事件监听器 [英] Hammer.js can't remove event listener
问题描述
我像这样创建锤子实例:
I create a hammer instance like so:
var el = document.getElementById("el");
var hammertime = Hammer(el);
然后我可以添加一个侦听器:
I can then add a listener:
hammertime.on("touch", function(e) {
console.log(e.gesture);
}
但是,由于以下操作,我无法删除此侦听器:
However I can't remove this listener because the following does nothing:
hammertime.off("touch");
我做错了什么?我如何摆脱锤子听众?Hammer.js文档目前还很差,因此除了存在 .on()
和 .off()
方法的事实之外,它没有任何解释.我不能使用jQuery版本,因为这是对性能至关重要的应用程序.
What am I doing wrong? How do I get rid of a hammer listener? The hammer.js docs are pretty poor at the moment so it explains nothing beyond the fact that .on()
and .off()
methods exist. I can't use the jQuery version as this is a performance critical application.
JSFiddle展示了这一点: http://jsfiddle.net/LSrgh/1/ >
JSFiddle to showcase this: http://jsfiddle.net/LSrgh/1/
推荐答案
好,我知道了.来源很简单,它正在做:
Ok, I figured it out. The source it's simple enough, it's doing:
on: function(t, e) {
for (var n = t.split(" "), i = 0; n.length > i; i++)
this.element.addEventListener(n[i], e, !1);
return this
},off: function(t, e) {
for (var n = t.split(" "), i = 0; n.length > i; i++)
this.element.removeEventListener(n[i], e, !1);
return this
}
这里要注意的事情(除了错误的文档),是 e
是 on
事件中的回调函数,所以您要做的是:
The thing to note here (apart from a bad documentation) it's that e
it's the callback function in the on
event, so you're doing:
this.element.addEventListener("touch", function() {
//your function
}, !1);
但是,在删除操作中,您不会传递回调,而是这样做:
But, in the remove, you don't pass a callback so you do:
this.element.removeEventListener("touch", undefined, !1);
因此,浏览器不知道您是否要取消绑定巫婆功能,您可以不使用匿名函数来解决此问题,就像我在其中所做的那样:
So, the browser doesn't know witch function are you trying to unbind, you can fix this not using anonymous functions, like I did in:
有关更多信息: JavaScript removeEventListener不起作用
这篇关于Hammer.js无法删除事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!