PageRenderTime 23ms CodeModel.GetById 15ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/static/eshq.js

http://github.com/biilmann/eventsource-broker
JavaScript | 40 lines | 31 code | 9 blank | 0 comment | 6 complexity | b2a39a7a903d34754533dbeb88d3bea5 MD5 | raw file
 1(function() {
 2  var origin = "$origin$";
 3
 4  var Sub = function(channel, options) {
 5    for (var i in options) {
 6      this[i] = options[i];
 7    };
 8    this.channel = channel;
 9  }
10
11  var subs = {};
12
13  var onMessage = function(event) {
14    if (event.origin !== origin) { return; }
15
16    var data = JSON.parse(event.data);
17    if (!data.eshqEvent) { return; }
18
19    var sub = subs[data.channel];
20    if (!sub) { return; }
21
22    if (sub[data.eshqEvent]) { sub[data.eshqEvent].call(null, data.originalEvent); }
23  };
24
25  window.addEventListener("message", onMessage, false);
26
27  var openChannel = function(channel) {
28      var iframe = document.createElement("iframe");
29      iframe.setAttribute("style", "display: none;");
30      iframe.setAttribute("src", origin + "/iframe?channel="+channel);
31      document.body.appendChild(iframe);
32  };
33
34  window.eshq = {
35    subscribe: function(channel, options) {
36      subs[channel] = new Sub(channel, options || {});
37      openChannel(channel);
38    }
39  };
40})();