如何克隆或重新调度DOM事件? [英] How to clone or re-dispatch DOM events?
问题描述
我正在寻找一种简单而抽象的克隆方式或重新调度DOM事件。我不感兴趣克隆DOM节点。
I'm looking for a simple and abstract way of cloning or re-dispatching DOM events only. I am not interested in cloning DOM nodes.
我已经尝试了一下,阅读了 DOM事件规范,我发现没有明确答案。
I've experimented a bit, read the DOM Events specification and I found no clear answer.
理想情况下,我正在寻找一些直截了当作为:
Ideally, I'm looking for something as straight-forward as:
handler = function(e){
document.getElementById("decoy").dispatchEvent(e)
}
document.getElementById("source").addEventListener("click", handler)
这个代码示例当然不起作用。有一个DOM异常,表示事件当前正在调度 - 显然。
This code example, of course, does not work. There's a DOM exception stating that the event is currently being dispatched - obviously.
我想避免手动创建新的事件与 document.createEvent ()
,初始化它们并进行调度。
I'd like to avoid manually creating new events with document.createEvent()
, initializing them and dispatching them.
这个用例有一个简单的解决方案吗?
Is there a simple solution to this use case?
推荐答案
我知道这个问题是老的,OP想避免创建/初始化方法,但是有一个比较简单的方式来复制事件:
I know, the question is old, and the OP wanted to avoid creating / initializing approach, but there's a relatively straightforward way to duplicate events:
new_event = new MouseEvent(old_event.type, old_event)
如果你想要的不仅仅是鼠标事件,你可以这样做:
If you want more than just mouse events, you could do something like this:
new_event = new old_event.constructor(old_event.type, old_event)
在原始上下文中:
handler = function(e) {
new_e = new e.constructor(e.type, e);
document.getElementById("decoy").dispatchEvent(new_e);
}
document.getElementById("source").addEventListener("click", handler);
(对于jQuery用户:您可能需要使用 e.originalEvent.constructor
而不是 e.constructor
)
(For jQuery users: you may need to use e.originalEvent.constructor
instead of e.constructor
)
这篇关于如何克隆或重新调度DOM事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!