Posted By

Nick___ on 01/22/10


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Nick___


Dump Object Properties 2


 / Published in: JavaScript
 

Cleaned-up version

  1. var dump = (function(){
  2.  
  3. var objects=[];
  4.  
  5. // html escape
  6. function htmlEsc (s)
  7. {
  8. return String(s).replace(/&/g,'&')
  9. .replace(/</g,'&lt;').replace(/\>/g,'&gt;');
  10. }
  11.  
  12. // get display name for object
  13. function oname (o)
  14. {
  15. if (o===undefined) return '<i>undefined</i>';
  16. if (o===null) return '<i>null</i>';
  17. var c = o.constructor;
  18. return '<span style="color:#666"> <i>' + typeof o + '</i> '
  19. +(c ? String(c).split('{')[0].substr(8) :'') + '</span> '
  20. +'<pre style="display:inline">' + htmlEsc(o) + '</pre>';
  21. }
  22.  
  23. // determine if object has props
  24. function hasprops (o)
  25. {
  26. for (undefined in o) return true; return false;
  27. }
  28.  
  29. // show non-dumped item
  30. function load (e)
  31. {
  32. e.hasData = true;
  33. e.style.display = 'block';
  34. dump(objects[e.getAttribute('obj')],1,e,true);
  35. return false;
  36. }
  37.  
  38. // toggle property list viz
  39. function toggle (e,rhs)
  40. {
  41. var n = rhs ? e.previousSibling : e.nextSibling;
  42. var s = n.style;
  43. if ((!n.hasData) && s.display == 'none') return load(n);
  44. n.hasData = true;
  45. s.display = s.display == 'none' ? 'block' : 'none';
  46. return false;
  47. }
  48.  
  49. // dump attributes
  50. function dump (o,limit,e,clicked)
  51. {
  52. var outer = false;
  53. if (e===undefined)
  54. {
  55. outer = true;
  56. e = document.createElement('div');
  57. e.style.font = '11px sans-serif';
  58. }
  59. if (outer || clicked)
  60. {
  61. e.val = "";
  62. e.write = function(s) {e.val += s}
  63. e.flush = function() {e.innerHTML += e.val; e.val = ''}
  64. }
  65. if (limit===undefined) limit = 3;
  66. var tab = '<br/\><a href="#" onclick="return dump.t(this)">'
  67. +'<b>{</b></a><div style="margin-left:1em'
  68. +(limit ? '' : ';display:none') +'"'
  69. +(limit ? '' : 'obj="'+objects.length+'" ') +'>';
  70. var end = '</div><a href="#" onclick="return dump.t(this,1)">'
  71. +'<b>}</b></a><br/\>';
  72. if (!limit)
  73. {
  74. if (!hasprops(o))
  75. return e.write(oname(o)+'<br/\>');
  76. objects.push(o);
  77. return e.write(oname(o)+tab+end);
  78. }
  79. if (!clicked) e.write(oname(o));
  80. var c = 0;
  81. for (var p in o)
  82. {
  83. if ((!clicked) && !c++) e.write(tab);
  84. e.write("<b>"+p+"</b> => ");
  85. dump(o[p], limit-1, e);
  86. }
  87. e.write(clicked ? "" : c ? end : "<br/\>");
  88. if (outer || clicked) e.flush();
  89. if (outer) document.body.appendChild(e);
  90. }
  91.  
  92. dump.t = toggle;
  93. return dump;
  94.  
  95. })();

Report this snippet  

You need to login to post a comment.