PageRenderTime 12ms CodeModel.GetById 2ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 0ms

/templates/eshq.js.st

http://github.com/biilmann/eventsource-broker
Unknown | 70 lines | 57 code | 13 blank | 0 comment | 0 complexity | 12c7715344abf4670bed4efcd18c2ace MD5 | raw file
 1(function() {
 2  var origin = "$origin$";
 3
 4	if (typeof(window.addEventListener) == "undefined") {
 5		window.addEventListener = function(name, fn) {
 6			window.attachEvent("on" + name, fn);
 7		};
 8	}
 9
10  var post = function(path, data, callback) {
11    var xhr = new XMLHttpRequest();
12    xhr.open('POST', path, true);
13    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
14    xhr.onreadystatechange = callback;
15    xhr.send(data);
16  };
17
18  var Sub = function(channel, options) {
19    for (var i in options) {
20      this[i] = options[i];
21    };
22    this.channel = channel;
23  }
24
25  var subs = {};
26
27  var onMessage = function(event) {
28    if (event.origin !== origin) { return; }
29
30    var data = JSON.parse(event.data);
31    if (!data.eshqEvent) { return; }
32
33    var sub = subs[data.channel];
34    if (!sub) { return; }
35
36    if (sub[data.eshqEvent]) { sub[data.eshqEvent].call(null, data.originalEvent); }
37  };
38
39  window.addEventListener("message", onMessage, false);
40
41  var getSocket = function(channel, url) {
42    post(url, "channel=" + channel, function() {
43      if (this.readyState == 4 && this.status == 200) {
44        var resp = JSON.parse(this.responseText);
45        openChannel(channel, resp.socket);
46      }
47    });
48  };
49
50  var openChannel = function(channel, socket) {
51      var iframe = document.createElement("iframe");
52      iframe.setAttribute("style", "display: none;");
53      iframe.setAttribute("src", origin + "/iframe?channel=" + channel + "&socket=" + socket + "&t=" + new Date().getTime());
54      document.body.appendChild(iframe);
55      subs[channel].frame = iframe;
56  };
57
58  window.eshq = {
59    open: function(channel, options) {
60      subs[channel] = new Sub(channel, options || {});
61      getSocket(channel, options.auth_url || "/eshq/socket");
62    },
63    send: function(channel, data) {
64      var sub = subs[channel];
65      if (!sub) throw "You must open a channel before sending to it";
66
67      sub.frame.contentWindow.postMessage(data, "*");
68    }
69  };
70})();