forked from EndMove/EndG-2048
51 lines
1.2 KiB
JavaScript
51 lines
1.2 KiB
JavaScript
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;
|
|
} |