aboutsummaryrefslogtreecommitdiffstats
path: root/src/Browser.js
blob: 6036884f4018499deb7e61bed8d4984c99c0a5b1 (plain)
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
//////////////////////////////
// Browser
//////////////////////////////

function Browser(location, XHR) {
  this.location = location;
  this.delay = 25;
  this.XHR = XHR;
  this.setTimeout = function(fn, delay) {
   window.setTimeout(fn, delay);
  };
  this.expectedUrl = location.href;
  this.listeners = [];
}

Browser.prototype = {
  xhr: function(method, url, callback){
    var xhr = new this.XHR();
    xhr.open(method, url, true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        callback(xhr.status, xhr.responseText);
      }
    };
    xhr.send('');
  },

  watchUrl: function(fn){
   this.listeners.push(fn);
  },

  startUrlWatcher: function() {
   var self = this;
   (function pull () {
     if (self.expectedUrl !== self.location.href) {
       foreach(self.listeners, function(listener){
         try {
           listener(self.location.href);
         } catch (e) {
           error(e);
         }
       });
       self.expectedUrl = self.location.href;
     }
     self.setTimeout(pull, self.delay);
   })();
  },

  setUrl: function(url) {
   var existingURL = this.location.href;
   if (!existingURL.match(/#/))
     existingURL += '#';
   if (existingURL != url)
     this.location.href = url;
  },

  getUrl: function() {
   return this.location.href;
  }
};