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

50 lines
1.2 KiB
JavaScript
Raw Normal View History

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