Skip to content

Instantly share code, notes, and snippets.

@ondrejmirtes
Created April 14, 2014 13:26
Show Gist options
  • Save ondrejmirtes/10647722 to your computer and use it in GitHub Desktop.
Save ondrejmirtes/10647722 to your computer and use it in GitHub Desktop.
var WebSocketWrapper = function(url) {
this.url = url;
this.registeredFunctions = {};
this.ws = null;
this.retry = true;
};
WebSocketWrapper.prototype.send = function(message) {
this.ws.send(JSON.stringify(message));
}
WebSocketWrapper.prototype.on = function(action, callback, scope) {
if (!scope) {
scope = window;
}
this.registeredFunctions[action] = {'callback': callback, 'scope': scope};
};
WebSocketWrapper.prototype.fireAction = function(action, params) {
if (!(action in this.registeredFunctions)) {
return;
}
var registeredFunction = this.registeredFunctions[action];
registeredFunction['callback'].call(
registeredFunction['scope'],
params
);
};
WebSocketWrapper.prototype.retryConnect = function() {
if (!this.retry) {
return;
}
this.connect();
}
WebSocketWrapper.prototype.connect = function() {
if (!WebSocketWrapper.isSupported()) {
return;
}
this.retry = true;
this.ws = new WebSocket(this.url);
var ws = this.ws;
var self = this;
ws.onopen = function() {
self.fireAction('onopen');
};
ws.onmessage = function(e) {
var data = JSON.parse(e.data);
self.fireAction(data['action'], data);
};
ws.onclose = function() {
self.fireAction('onclose');
setTimeout(function() {
self.retryConnect();
}, 2500);
};
if ('start' in ws) {
ws.start();
}
};
WebSocketWrapper.prototype.disconnect = function() {
this.retry = false;
this.ws.close();
};
WebSocketWrapper.isSupported = function() {
return 'WebSocket' in window;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment