EndG-2048-multiplayer/assets/js/remote_storage_manager.js

51 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

2023-03-25 19:34:30 +01:00
function RemoteStorageManager() {
this.storage = new WebSocket("ws://localhost/");
openListeners = [];
dataListeners = [];
this.bestScore = 0;
this.storage.onopen = function(){
this.connected = true;
openListeners.forEach(listener => listener());
}
this.storage.onmessage = function(e){
let data = JSON.parse(e.data);
let list = dataListeners[data.game];
if(list !== undefined) list.forEach(listener => listener(data));
console.log(data);
if(data.action === "bestScore"){
this.bestScore = data.value;
}
}
this.openListeners = openListeners;
this.dataListeners = dataListeners;
}
RemoteStorageManager.prototype.onConnected = function(func){
if(this.connected){
func();
return;
}
this.openListeners.push(func);
}
RemoteStorageManager.prototype.onData = function(func, game){
let listeners = this.dataListeners[game];
if(listeners == undefined){
listeners = [];
this.dataListeners[game] = listeners;
}
listeners.push(func);
}
RemoteStorageManager.prototype.sendAction = function(action, value){
this.storage.send(JSON.stringify(value === undefined ? {action:action} : {action:action,value:value}));
}
RemoteStorageManager.prototype.getBestScore = function(){
return this.bestScore;
}