Implement the messaging module for good using the async monad for message reception
This commit is contained in:
parent
0ec7c4d1ee
commit
aa6fe74a6b
1 changed files with 29 additions and 39 deletions
|
@ -1,55 +1,45 @@
|
|||
function Messaging() {
|
||||
var ws = new WebSocket('ws://' + window.location.hostname + '/play/');
|
||||
var keepAlivePeriod = 20000;
|
||||
var routes = {callbacks: [], children: {}};
|
||||
var receiveHook;
|
||||
var queue = []
|
||||
ws.addEventListener('message', messageListener);
|
||||
|
||||
return {
|
||||
addEventListener: addEventListener,
|
||||
send: send,
|
||||
start: start
|
||||
}
|
||||
|
||||
function get(obj, path, write) {
|
||||
write = write || false;
|
||||
if(path.length < 1) {
|
||||
return obj;
|
||||
} else {
|
||||
if(obj.children[path[0]] == undefined && write) {
|
||||
obj.children[path[0]] = {callbacks: [], children: {}};
|
||||
}
|
||||
if(obj.children[path[0]] != undefined) {
|
||||
return get(obj.children[path[0]], path.slice(1), write);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addEventListener(path, callback) {
|
||||
var route = get(routes, path, true);
|
||||
route.callbacks.push(callback);
|
||||
receive: receive,
|
||||
send: send
|
||||
}
|
||||
|
||||
function messageListener(event) {
|
||||
var o = JSON.parse(event.data);
|
||||
var path = [];
|
||||
var tmp = o;
|
||||
while(tmp != undefined && tmp.tag != undefined) {
|
||||
path.push(tmp.tag);
|
||||
tmp = tmp.message;
|
||||
}
|
||||
var route = get(routes, path);
|
||||
if(route != undefined && route.callbacks != undefined) {
|
||||
route.callbacks.forEach(function(f) {f(o);});
|
||||
if(o.tag == "Error") {
|
||||
console.log(o.error);
|
||||
} else {
|
||||
debug.textContent = event.data;
|
||||
if(receiveHook != undefined) {
|
||||
receiveHook(o);
|
||||
} else {
|
||||
queue.push(o);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function start() {
|
||||
//ping();
|
||||
addEventListener(["Pong"], ping);
|
||||
ws.addEventListener('message', messageListener);
|
||||
function receive(predicate) {
|
||||
predicate = predicate || function() {return true;};
|
||||
return function(f) {
|
||||
for(var i = 0; i < queue.length; i++) {
|
||||
if(predicate(queue[i])) {
|
||||
return f(queue.splice(i, 1)[0]);
|
||||
}
|
||||
}
|
||||
receiveHook = function(message) {
|
||||
if(predicate(message)) {
|
||||
receiveHook = null;
|
||||
f(message);
|
||||
} else {
|
||||
queue.push(o);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function send(o) {
|
||||
|
|
Loading…
Reference in a new issue