Return to Snippet

Revision: 22798
at January 22, 2010 13:43 by Nick___


Initial Code
var dump = (function(){

  var objects=[];
  
  // html escape
  function htmlEsc (s) 
  { 
    return String(s).replace(/&/g,'&')
      .replace(/</g,'&lt;').replace(/\>/g,'&gt;');
  }
  
  // get display name for object
  function oname (o) 
  { 
    if (o===undefined) return '<i>undefined</i>';
    if (o===null) return '<i>null</i>';
    var c = o.constructor;
    return '<span style="color:#666"> <i>' + typeof o + '</i> '
      +(c ? String(c).split('{')[0].substr(8) :'') + '</span> '
      +'<pre style="display:inline">' + htmlEsc(o) + '</pre>';
  }
  
  // determine if object has props
  function hasprops (o) 
  { 
    for (undefined in o) return true; return false; 
  }
  
  // show non-dumped item
  function load (e) 
  { 
    e.hasData = true;
    e.style.display = 'block';
    dump(objects[e.getAttribute('obj')],1,e,true);
    return false; 
  }
  
  // toggle property list viz
  function toggle (e,rhs) 
  { 
    var n = rhs ? e.previousSibling : e.nextSibling;
    var s = n.style;
    if ((!n.hasData) && s.display == 'none') return load(n);
    n.hasData = true;
    s.display = s.display == 'none' ? 'block' : 'none';
    return false; 
  }

  // dump attributes
  function dump (o,limit,e,clicked) 
  {
    var outer = false;
    if (e===undefined) 
    {
      outer = true;
      e = document.createElement('div');
      e.style.font = '11px sans-serif'; 
    }
    if (outer || clicked) 
    {
      e.val = "";
      e.write = function(s) {e.val += s}
      e.flush = function() {e.innerHTML += e.val; e.val = ''} 
    }
    if (limit===undefined) limit = 3;
    var tab = '<br/\><a href="#" onclick="return dump.t(this)">'
      +'<b>{</b></a><div style="margin-left:1em'
      +(limit ? '' : ';display:none') +'"'
      +(limit ? '' : 'obj="'+objects.length+'" ') +'>';
    var end = '</div><a href="#" onclick="return dump.t(this,1)">'
      +'<b>}</b></a><br/\>';
    if (!limit) 
    {
      if (!hasprops(o))
        return e.write(oname(o)+'<br/\>');
      objects.push(o);
      return e.write(oname(o)+tab+end); 
    }
    if (!clicked) e.write(oname(o));
    var c = 0;
    for (var p in o) 
    {
      if ((!clicked) && !c++) e.write(tab);
      e.write("<b>"+p+"</b> => ");
      dump(o[p], limit-1, e); 
    }
    e.write(clicked ? "" : c ? end : "<br/\>");
    if (outer || clicked) e.flush();  
    if (outer) document.body.appendChild(e); 
  }

  dump.t = toggle;
  return dump;

})();

Initial URL

                                

Initial Description
Cleaned-up version

Initial Title
Dump Object Properties 2

Initial Tags

                                

Initial Language
JavaScript