Cloning a javascript event object

Does anyone know how to make a deep copy / clone of my own javascript event object? I know that I can create a new event object and set the corresponding properties manually according to the original event, but it would be much easier if there was a way to clone.

+7
source share
3 answers

For your purposes, I just make it the prototype of the new constructor of objects and redefine the ones you want to change. Cloning in JS becomes messy due to a circular link problem, so this may not be the fast and dirty solution you were hoping for.

function cloneEventObj(eventObj, overrideObj){ if(!overrideObj){ overrideObj = {}; } function EventCloneFactory(overProps){ for(var x in overProps){ this[x] = overProps[x]; } } EventCloneFactory.prototype = eventObj; return new EventCloneFactory(overrideObj); } //So add your override properties via an object $el.click(function(e){ var newEventObj = cloneEventObj( e, { target:document.body } ); doSomething(newEventObj); }); //or just stick 'em on manually after spitting the object out /*... var newEventObj = cloneEventObj(e); newEventObj.target = document.body ...*/ 

In this case, the "cloned" object is the prototype of the object of the new object. 'this is.' properties are checked before the prototype object to be redefined. Or you can just attach properties after creating the object.

+9
source

Above code will not copy any getters / setters properly. Try:

 function cloneEvent(e) { if (e===undefined || e===null) return undefined; function ClonedEvent() {}; let clone=new ClonedEvent(); for (let p in e) { let d=Object.getOwnPropertyDescriptor(e, p); if (d && (d.get || d.set)) Object.defineProperty(clone, p, d); else clone[p] = e[p]; } Object.setPrototypeOf(clone, e); return clone; } 
+5
source

Cofifus-inspired answer, I just do it

 function cloneEvent(type, event) { var evt = new Event(type); return Object.setPrototypeOf(evt,event); } 
0
source

All Articles