Blame view

src/main/webapp/libs/offline/js/reconnect.js 1.78 KB
caiyongsong committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
(function() {
  var down, next, nope, rc, reset, retryIntv, tick, tryNow, up;

  if (!window.Offline) {
    throw new Error("Offline Reconnect brought in without offline.js");
  }

  rc = Offline.reconnect = {};

  retryIntv = null;

  reset = function() {
    var ref;
    if ((rc.state != null) && rc.state !== 'inactive') {
      Offline.trigger('reconnect:stopped');
    }
    rc.state = 'inactive';
    return rc.remaining = rc.delay = (ref = Offline.getOption('reconnect.initialDelay')) != null ? ref : 3;
  };

  next = function() {
    var delay, ref;
    delay = (ref = Offline.getOption('reconnect.delay')) != null ? ref : Math.min(Math.ceil(rc.delay * 1.5), 3600);
    return rc.remaining = rc.delay = delay;
  };

  tick = function() {
    if (rc.state === 'connecting') {
      return;
    }
    rc.remaining -= 1;
    Offline.trigger('reconnect:tick');
    if (rc.remaining === 0) {
      return tryNow();
    }
  };

  tryNow = function() {
    if (rc.state !== 'waiting') {
      return;
    }
    Offline.trigger('reconnect:connecting');
    rc.state = 'connecting';
    return Offline.check();
  };

  down = function() {
    if (!Offline.getOption('reconnect')) {
      return;
    }
    reset();
    rc.state = 'waiting';
    Offline.trigger('reconnect:started');
    return retryIntv = setInterval(tick, 1000);
  };

  up = function() {
    if (retryIntv != null) {
      clearInterval(retryIntv);
    }
    return reset();
  };

  nope = function() {
    if (!Offline.getOption('reconnect')) {
      return;
    }
    if (rc.state === 'connecting') {
      Offline.trigger('reconnect:failure');
      rc.state = 'waiting';
      return next();
    }
  };

  rc.tryNow = tryNow;

  reset();

  Offline.on('down', down);

  Offline.on('confirmed-down', nope);

  Offline.on('up', up);

}).call(this);