1
0
forked from MTSR/mapserver
mapserver/server/static/js/WebSocketChannel.js

45 lines
984 B
JavaScript
Raw Normal View History

2019-01-29 20:08:54 +03:00
var WebSocketChannel = (function(){
'use strict';
var wsUrl = location.protocol.replace("http", "ws") + "//" + location.host + location.pathname.substring(0, location.pathname.lastIndexOf("/")) + "/api/ws";
var listenerMap = {/* type -> [listeners] */};
function addListener(type, listener){
var list = listenerMap[type];
if (!list){
list = [];
listenerMap[type] = list;
}
list.push(listener);
}
function connect(){
var ws = new WebSocket(wsUrl);
ws.onmessage = function(e){
var event = JSON.parse(e.data);
//rendered-tile, mapobject-created, mapobjects-cleared
var listeners = listenerMap[event.type];
if (listeners){
listeners.forEach(function(listener){
listener(event.data);
});
}
}
ws.onerror = function(){
//reconnect after some time
setTimeout(connect, 1000);
}
}
return {
connect: connect,
addListener: addListener
};
}());