/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. var Sub = function(channel, options) {
  4. for (var i in options) {
  5. this[i] = options[i];
  6. };
  7. this.channel = channel;
  8. }
  9. var subs = {};
  10. var onMessage = function(event) {
  11. if (event.origin !== origin) { return; }
  12. var data = JSON.parse(event.data);
  13. if (!data.eshqEvent) { return; }
  14. var sub = subs[data.channel];
  15. if (!sub) { return; }
  16. if (sub[data.eshqEvent]) { sub[data.eshqEvent].call(null, data.originalEvent); }
  17. };
  18. window.addEventListener("message", onMessage, false);
  19. var openChannel = function(channel) {
  20. var iframe = document.createElement("iframe");
  21. iframe.setAttribute("style", "display: none;");
  22. iframe.setAttribute("src", origin + "/iframe?channel="+channel);
  23. document.body.appendChild(iframe);
  24. };
  25. window.eshq = {
  26. subscribe: function(channel, options) {
  27. subs[channel] = new Sub(channel, options || {});
  28. openChannel(channel);
  29. }
  30. };
  31. })();