-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
96 lines (89 loc) · 2.81 KB
/
app.js
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
function initViewer(ref) {
var proto = (window.location.protocol == "https:")? "wss://": "ws://";
var ws = new WebSocket(proto+window.location.host+"/websocket/?id="+ref);
console.log("Connecting...");
ws.onopen = function(evt) {
console.log("Connected!");
};
ws.onmessage = function(evt) {
var change = JSON.parse(evt.data);
console.log(change);
var $tag = $('#'+change.id);
change.object = $tag;
if (change.type === 'refresh') {
$tag.html(change.value);
} else if (change.type === 'trigger') {
$tag.trigger(change.value);
} else if (change.type === 'added') {
$tag.append($(change.value));
} else if (change.type === 'removed') {
$tag.find('#'+change.value).remove();
} else if (change.type === 'update') {
if (change.name==="text") {
var node = $tag.contents().get(0);
if (!node) {
node = document.createTextNode("");
$tag.append(node);
}
node.nodeValue = change.value;
} else if (change.name==="attrs") {
$.map(change.value,function(v,k){
$tag.prop(k,v);
});
} else {
if (change.name==="cls") {
change.name = "class";
}
$tag.prop(change.name,change.value);
}
} else if (change.type === 'error') {
console.log(change.message);
} else if (change.type === 'reload') {
location.reload();
} else {
console.log("Unknown change type");
}
};
ws.onclose = function(evt) {
console.log("Disconnected!");
};
function sendEvent(change) {
console.log(change);
ws.send(JSON.stringify(change));
};
function sendNodeValue(){
sendEvent({
'id':this.id,
'type':'update',
'name':'value',
'value':$(this).val(),
});
};
$(document).on('click', '[clickable]',function(e){
e.preventDefault();
sendEvent({
'id':this.id,
'type':'event',
'name':'clicked'
});
});
$(document).on('change', ":checkbox", function(){
sendEvent({
'id':this.id,
'type':'update',
'name':'checked',
'value':($(this).prop('checked'))?'checked':'',
});
});
$(document).on('change', "select", sendNodeValue);
$(document).on('input', 'input', sendNodeValue);
$(document).on('change', 'textarea', function() {
sendEvent({
'id':this.id,
'type':'update',
'name':'text',
'value':$(this).val(),
});
});
return ws;
}