每当用户移动时,我都会发生一些事情,为此,我设置了三个事件侦听器:
document.addEventListener('mousemove', this.doThing)
document.addEventListener('click', this.doThing)
document.addEventListener('keydown', this.doThing)
哪些最终还需要删除:
document.removeEventListener('mousemove', this.doThing)
document.removeEventListener('click', this.doThing)
document.removeEventListener('keydown', this.doThing)
问题是,它们都在做完全相同的事情,所以我想知道是否有更好的方法将它们分组为单个添加和删除事件侦听器。或者,也许有一种方法可以涵盖用户的任何移动/互动吗?
答案 0 :(得分:1)
您可以执行以下操作:
["mousemove", "click", "keydown"].forEach(evt => document.addEventListener(evt, this.doThing));
["mousemove", "click", "keydown"].forEach(evt => document.removeEventListener(evt, this.doThing));
带有lambda的简单通用版本可能是:
let addHandlers = (events, handler) => events.forEach(evt => document.addEventListener(evt, handler))
let removeHandlers = (events, handler) => events.forEach(evt => document.addEventListener(evt, handler))
addHandlers(["mousemove", "click"], this.doThing);
removeHandlers(["mousemove", "click"], this.doThing);
答案 1 :(得分:1)
您可以提供一个用空格分隔的事件字符串,并循环遍历每个事件。像jQuery.on()
这样的大多数库都执行类似的操作。
function setEventsToDocument(events, callback) {
events.split(' ').forEach(event => {
document.addEventListener(event, callback)
})
}
function removeEventsFromDocument(events, callback) {
events.split(' ').forEach(event => {
document.removeEventListener(event, callback)
})
}
setEventsToDocument('mousemove click keydown', callback)
removeEventsFromDocument('mousemove click keydown', callback)
答案 2 :(得分:1)
是的,创建一个handleEvent
成员函数并提供this
作为事件处理程序:
class Thing {
constructor(el) {
this.el = el;
this.el.addEventListener("mouseover", this);
this.el.addEventListener("click", this);
}
handleEvent(e) {
switch (e.type) {
case "mouseover":
console.log("mouseover");
break;
case "click":
console.log("click");
break;
}
}
};
const thing = new Thing(document.getElementById("foo"));
<button id="foo">Hello</button>