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

55 lines
1.2 KiB
JavaScript
Raw Normal View History

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