]> git.mar77i.info Git - hublib/blob - webroot/common.js
big cleanup and refactoring #1
[hublib] / webroot / common.js
1 (function () {
2 var domconf_event_prefix = "event_";
3 function domconf(domobj, obj) {
4 var key;
5 for (key in obj) {
6 if (key.substring(0, domconf_event_prefix.length) == domconf_event_prefix) {
7 domobj.addEventListener(
8 key.substring(domconf_event_prefix.length), obj[key]
9 );
10 } else {
11 domobj.setAttribute(key, obj[key])
12 }
13 }
14 return domobj;
15 }
16
17 function tag(tag_name, obj) {
18 return domconf(document.createElement(tag_name), obj);
19 }
20
21 function HubClient(ws_uri, open, close, message) {
22 this.close = close.bind(this);
23 this.message = message.bind(this);
24 this.open = open.bind(this);
25 this.ws = domconf(
26 new WebSocket(
27 {"http:": "ws:", "https:": "wss:"}[window.location.protocol] +
28 "//" +
29 window.location.host +
30 ws_uri
31 ),
32 {
33 "event_close": this.close,
34 "event_message": this.message,
35 "event_open": this.open,
36 },
37 );
38 this.send = this.ws.send.bind(this.ws);
39 }
40
41 function write(output, msg) {
42 if (output.childNodes.length > 0) {
43 output.append(tag("br"));
44 }
45 if (typeof msg !== "string") {
46 msg = String(msg);
47 }
48 output.append(document.createTextNode(msg));
49 }
50
51 function setup(callback) {
52 domconf(
53 document,
54 {
55 "event_readystatechange": function (event) {
56 if (!event) {
57 event = window.event;
58 }
59 if (event.target.readyState !== "complete") {
60 return;
61 }
62 callback(event);
63 }
64 },
65 );
66 }
67
68 function make_key_event(callback) {
69 var wrapper = function (event) {
70 event = event || window.event;
71 callback(event, event.target || event.srcElement, event.code || event.key);
72 };
73 return wrapper;
74 }
75
76 function input_with_keydown_event(callback) {
77 return common.tag("input", {"event_keydown": make_key_event(callback)});
78 }
79
80 window.common = {
81 "tag": tag,
82 "HubClient": HubClient,
83 "write": write,
84 "setup": setup,
85 "input_with_keydown_event": input_with_keydown_event,
86 };
87 }());