Anybody know how to do a deep copy/cloning of a native javascript event object? I know I can create a new event object and set the appropriate properties manually to match the original event, but it'd be much easier if there's a way to just clone.
To clone an eventFrom Define an event window, select the event you want to clone. Click Clone to open the Event Clone window. Enter a new event code for the cloned event. Click Save.
Cloning a JavaScript object is a task that is used mostly because we do not want to create the same object if the same object already exists. There are few ways. By iterate through each property and copy them to new object. Using JSON method as the source object MUST be JSON safe.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With