How to stringify event object?

Tar picture Tar · Jul 18, 2012 · Viewed 23k times · Source

JSON.stringify(eventObject);

gives:

TypeError: Converting circular structure to JSON


dojox.json.ref.toJson(eventObject);

gives:

TypeError: Accessing selectionEnd on an input element that cannot have a selection.


Is there some library/code ready to use to accomplish it ?

Answer

fresskoma picture fresskoma · Jul 18, 2012

You won't be able to serialize an event object with JSON.stringify, because an event object contains references to DOM nodes, and the DOM has circular references all over the place (e.g. child/parent relationships). JSON can't handle these by default, so you're a bit out of luck there.

I'd suggest to look at How to serialize DOM node to JSON even if there are circular references? which has a few suggestions on how to serialize a DOM node. Also, the following questions seem to have useful information:

JSON libraries able to handle circular references seem to be

Alternatively, you could delete all references to DOM nodes if you don't need them, and then serialize the object. You shouldn't do this after all. See @PointedEars comment :)