Created
March 17, 2016 11:30
-
-
Save forsaken1/6223ed86422c0996634b to your computer and use it in GitHub Desktop.
Small wrapper over WebSocket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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