Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cloning javascript event object

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.

like image 988
paul smith Avatar asked Sep 24 '12 22:09

paul smith


People also ask

How do you clone an event?

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.

Why do we clone object in JavaScript?

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.


1 Answers

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;
}
like image 195
kofifus Avatar answered Sep 24 '22 23:09

kofifus