sigma.parsers.json.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. ;(function(undefined) {
  2. 'use strict';
  3. if (typeof sigma === 'undefined')
  4. throw 'sigma is not declared';
  5. // Initialize package:
  6. sigma.utils.pkg('sigma.parsers');
  7. sigma.utils.pkg('sigma.utils');
  8. /**
  9. * Just an XmlHttpRequest polyfill for different IE versions.
  10. *
  11. * @return {*} The XHR like object.
  12. */
  13. sigma.utils.xhr = function() {
  14. if (window.XMLHttpRequest)
  15. return new XMLHttpRequest();
  16. var names,
  17. i;
  18. if (window.ActiveXObject) {
  19. names = [
  20. 'Msxml2.XMLHTTP.6.0',
  21. 'Msxml2.XMLHTTP.3.0',
  22. 'Msxml2.XMLHTTP',
  23. 'Microsoft.XMLHTTP'
  24. ];
  25. for (i in names)
  26. try {
  27. return new ActiveXObject(names[i]);
  28. } catch (e) {}
  29. }
  30. return null;
  31. };
  32. /**
  33. * This function loads a JSON file and creates a new sigma instance or
  34. * updates the graph of a given instance. It is possible to give a callback
  35. * that will be executed at the end of the process.
  36. *
  37. * @param {string} url The URL of the JSON file.
  38. * @param {object|sigma} sig A sigma configuration object or a sigma
  39. * instance.
  40. * @param {?function} callback Eventually a callback to execute after
  41. * having parsed the file. It will be called
  42. * with the related sigma instance as
  43. * parameter.
  44. */
  45. sigma.parsers.json = function(url, sig, callback) {
  46. var graph,
  47. xhr = sigma.utils.xhr();
  48. if (!xhr)
  49. throw 'XMLHttpRequest not supported, cannot load the file.';
  50. xhr.open('GET', url, true);
  51. xhr.onreadystatechange = function() {
  52. if (xhr.readyState === 4) {
  53. graph = JSON.parse(xhr.responseText);
  54. // Update the instance's graph:
  55. if (sig instanceof sigma) {
  56. sig.graph.clear();
  57. sig.graph.read(graph);
  58. // ...or instantiate sigma if needed:
  59. } else if (typeof sig === 'object') {
  60. sig.graph = graph;
  61. sig = new sigma(sig);
  62. // ...or it's finally the callback:
  63. } else if (typeof sig === 'function') {
  64. callback = sig;
  65. sig = null;
  66. }
  67. // Call the callback if specified:
  68. if (callback)
  69. callback(sig || graph);
  70. }
  71. };
  72. xhr.send();
  73. };
  74. }).call(this);