Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

javascript - How to clone or re-dispatch DOM events?

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.

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)

This code example, of course, does not work. There's a DOM exception stating that the event is currently being dispatched - obviously.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

And in the original context:

handler = function(e) {
  new_e = new e.constructor(e.type, e);
  document.getElementById("decoy").dispatchEvent(new_e);
}
document.getElementById("source").addEventListener("click", handler);

(For jQuery users: you may need to use e.originalEvent.constructor instead of e.constructor)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...