Skip to content

Instantly share code, notes, and snippets.

@SkyzohKey
Last active April 17, 2017 21:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SkyzohKey/447ad62f368790e5400508f4b0d3f371 to your computer and use it in GitHub Desktop.
Save SkyzohKey/447ad62f368790e5400508f4b0d3f371 to your computer and use it in GitHub Desktop.
EventSocket.js - A JSON event based client-side websocket wrapper.
/**
* @class EventSocket - A JSON event based client-side websocket wrapper.
* @param {String} scheme - The websocket server address scheme, can be `ws`, `wss`, `http`, `https`, whatever...
* @param {String} host - The websocket server ip address.
* @param {String} port - The websocket server port.
**/
function EventSocket (scheme, host, port) {
this.uri = [ scheme, '://', host, ':', port ].join('');
this.callbacks = {};
this.socket = null;
this.connected = false;
this._init();
}
/**
* @private init - This method has to initialize a socket and to bind the related events.
**/
EventSocket.prototype._init = function () {
this.socket = new WebSocket(this.uri);
// When the socket is opened.
this.socket.onopen = function () {
this.connected = true;
this.trigger('open', null);
};
// Once we get a message on socket.
this.socket.onmessage = function (event) {
var json = JSON.parse(event.data);
this.trigger(json.event, json.data);
};
// When an error occur.
this.socket.onerror = function () {
this.trigger('error', null);
};
// When the socket is closed/destructed.
this.socket.onclose = function (event) {
this.connected = false;
this.trigger('close', event);
};
};
/**
* @public trigger - Trigger an already bound event.
* @note Throw an Error if the triggered event wasn't bound before.
* @param {String} event - The event name.
* @param {Mixed} data - The data to send while triggering the event.
* @return {Object} this - Returns an instance of this, for chainability.
**/
EventSocket.prototype.trigger = function (event, data) {
var handlers = this.callbacks[event];
if (typeof handlers == 'undefined') { // If we doesn't have a callback for that event let's throw an error.
throw new Error('Event ' + event + ' was not bound to an EventSocket thus cannot be triggered.');
}
for (var i = 0; i < handlers.length; i++) {
handlers[i](data); // Trigger the handler.
}
return this;
};
/**
* @public bind - Bind an event and register a callback for it.
* @note An event can have multiple callbacks, just call bind with the same event name but with different callbacks.
* @param {String} event - The event name.
* @param {Function} callback - The callback function called once the event gets triggered.
* @return {Object} this - Returns an instance of this, for chainability.
**/
EventSocket.prototype.bind = function (event, callback) {
this.callbacks[event] = this.callbacks[event] || [];
this.callbacks[event].push(callback);
return this; // Make the function chainable.
};
/**
* @public trigger - Trigger an already bound event.
* @note Throw an Error if the websocket wasn't started.
* @param {String} event - The event name.
* @param {Mixed} data - The data to send.
* @return {Object} this - Returns an instance of this, for chainability.
**/
EventSocket.prototype.send = function (event, data) {
if (this.connected == false) { // Sending stuff while not connected is stupid, let's throw an error in that case.
throw new Error('Cannot send a payload while not connected to a WebSocket server.');
}
var payload = JSON.stringify({ event: event, data: data });
this.socket.send(payload);
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment