Thursday, May 15, 2008

Introduction

This script can dump any type of Javascript data (or most), thus, generating a string out of the received information.
It's specially useful when creating some kind of console or logger.
Also, it can be used for the development stage, when you need to inspect things on browsers that lack a good console.

How to use

Very simple:

var dumped = jsDump.parse( ... );

Instead of '...', you need to put the data that you want to dump.
That could be an array, a date, the document, an array of arrays, etc.
The variable 'dumped' will now contain a string with the dumped version of your data.

Settings

These are the things you can configure:

HTML

(boolean) If true, the data will be escaped for html output, the default setting is false.
Note that the script won't escape all the text, only the parts added by the script (indentation, new lines, dumped nodes), it won't alter original strings, etc.

indentChar

(string) This is the unit of indentation, by default it is 4 whitespaces.
Keep this agnostic from the HTML mode, it will escape spaces and tabs by itself.

multiline

(boolean) Whether to generate multiline code. The default is true. This is specially relevant when dumping collections.

DOMAttrs

(Object) This contains a map of attributes, that need to be dumped from HTML nodes.
The keys must be the names to be showed. The values, the real name of the attribute contained in the node.
By default, 'id', 'name' and 'class' are dumped (only if not empty).

To modify these settings, just do (f.e):

jsDump.HTML = true;

This needs to be done before calling .parse().

More methods

jsDump also contains a method, jsDump.typeOf, that is used internally to sniff the type of what you send.
You can use this function for your own code, it'll make an advanced typeof.
To modify the way a certain kind of data is dumped, you must set that using the method 'setParser'.
The 'parser' can be a string, or a function. Use a string if the output is always the same, otherwise, use a function. It will receive the object as argument and must return the parsed string.

To see all the data types, check the source, no gain on listing them all here.
Lastly, you can create your custom types, by just adding them to the list, then, inside a parser function, you can call the method .parse() and pass, as second argument, the custom data type.
This will force the script to use that type, instead of sniffing it from the data.

Wanted to point out 1 false-positive that I found if it helps anyone else out. In the this.typeOf function of the library, an array that has been treated like an object can sometimes be flagged as a node-list. To workaround this, consider changing