Skip to content

Instantly share code, notes, and snippets.

@forsaken1
Created March 17, 2016 11:30
Show Gist options
  • Save forsaken1/6223ed86422c0996634b to your computer and use it in GitHub Desktop.
Save forsaken1/6223ed86422c0996634b to your computer and use it in GitHub Desktop.
Small wrapper over WebSocket
function SocketIO(url) {
this.socket = new WebSocket(url);
this.actions = {};
var self = this;
this.socket.onmessage = function(event) {
var name, message;
[name, message] = self.parse_data(event.data);
self.actions[name](message)
}
}
SocketIO.prototype.on = function(name, action) {
this.actions[name] = action;
}
SocketIO.prototype.emit = function(name, message) {
var json_message = { name: name, message: message };
this.socket.send(JSON.stringify(json_message));
}
SocketIO.prototype.parse_data = function(data) {
var json_data = JSON.parse(data);
return [json_data.name, json_data.message];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment