util.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. var util = {
  2. debug: false,
  3. inherits: function(ctor, superCtor) {
  4. ctor.super_ = superCtor;
  5. ctor.prototype = Object.create(superCtor.prototype, {
  6. constructor: {
  7. value: ctor,
  8. enumerable: false,
  9. writable: true,
  10. configurable: true
  11. }
  12. });
  13. },
  14. extend: function(dest, source) {
  15. for(var key in source) {
  16. if(source.hasOwnProperty(key)) {
  17. dest[key] = source[key];
  18. }
  19. }
  20. return dest;
  21. },
  22. pack: BinaryPack.pack,
  23. unpack: BinaryPack.unpack,
  24. randomPort: function() {
  25. return Math.round(Math.random() * 60535) + 5000;
  26. },
  27. log: function () {
  28. if (util.debug) {
  29. for (var i = 0; i < arguments.length; i++) {
  30. console.log('*', i, '-- ', arguments[i]);
  31. }
  32. }
  33. },
  34. setZeroTimeout: (function(global) {
  35. var timeouts = [];
  36. var messageName = 'zero-timeout-message';
  37. // Like setTimeout, but only takes a function argument. There's
  38. // no time argument (always zero) and no arguments (you have to
  39. // use a closure).
  40. function setZeroTimeoutPostMessage(fn) {
  41. timeouts.push(fn);
  42. global.postMessage(messageName, '*');
  43. }
  44. function handleMessage(event) {
  45. if (event.source == global && event.data == messageName) {
  46. if (event.stopPropagation) {
  47. event.stopPropagation();
  48. }
  49. if (timeouts.length) {
  50. timeouts.shift()();
  51. }
  52. }
  53. }
  54. if (global.addEventListener) {
  55. global.addEventListener('message', handleMessage, true);
  56. } else if (global.attachEvent) {
  57. global.attachEvent('onmessage', handleMessage);
  58. }
  59. return setZeroTimeoutPostMessage;
  60. }(this)),
  61. blobToArrayBuffer: function(blob, cb){
  62. var fr = new FileReader();
  63. fr.onload = function(evt) {
  64. cb(evt.target.result);
  65. };
  66. fr.readAsArrayBuffer(blob);
  67. },
  68. blobToBinaryString: function(blob, cb){
  69. var fr = new FileReader();
  70. fr.onload = function(evt) {
  71. cb(evt.target.result);
  72. };
  73. fr.readAsBinaryString(blob);
  74. },
  75. binaryStringToArrayBuffer: function(binary) {
  76. var byteArray = new Uint8Array(binary.length);
  77. for (var i = 0; i < binary.length; i++) {
  78. byteArray[i] = binary.charCodeAt(i) & 0xff;
  79. }
  80. return byteArray.buffer;
  81. }
  82. };