util.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var util = {
  2. inherits: function(ctor, superCtor) {
  3. ctor.super_ = superCtor;
  4. ctor.prototype = Object.create(superCtor.prototype, {
  5. constructor: {
  6. value: ctor,
  7. enumerable: false,
  8. writable: true,
  9. configurable: true
  10. }
  11. });
  12. },
  13. extend: function(dest, source) {
  14. for(var key in source) {
  15. if(source.hasOwnProperty(key)) {
  16. dest[key] = source[key];
  17. }
  18. }
  19. return dest;
  20. },
  21. pack: BinaryPack.pack,
  22. unpack: BinaryPack.unpack,
  23. randomPort: function() {
  24. return Math.round(Math.random() * 60535) + 5000;
  25. },
  26. log: function () {
  27. if (debug) {
  28. for (var i = 0; i < arguments.length; i++) {
  29. console.log('*', i, '-- ', arguments[i]);
  30. }
  31. }
  32. },
  33. setZeroTimeout: (function(global) {
  34. var timeouts = [];
  35. var messageName = 'zero-timeout-message';
  36. // Like setTimeout, but only takes a function argument. There's
  37. // no time argument (always zero) and no arguments (you have to
  38. // use a closure).
  39. function setZeroTimeoutPostMessage(fn) {
  40. timeouts.push(fn);
  41. global.postMessage(messageName, '*');
  42. }
  43. function handleMessage(event) {
  44. if (event.source == global && event.data == messageName) {
  45. if (event.stopPropagation) {
  46. event.stopPropagation();
  47. }
  48. if (timeouts.length) {
  49. timeouts.shift()();
  50. }
  51. }
  52. }
  53. if (global.addEventListener) {
  54. global.addEventListener('message', handleMessage, true);
  55. } else if (global.attachEvent) {
  56. global.attachEvent('onmessage', handleMessage);
  57. }
  58. return setZeroTimeoutPostMessage;
  59. }(this))
  60. };