Skip to content

Instantly share code, notes, and snippets.

@javaguirre
Last active February 5, 2016 08:28
Show Gist options
  • Save javaguirre/8c55bb90ab7eedfc0c7e to your computer and use it in GitHub Desktop.
Save javaguirre/8c55bb90ab7eedfc0c7e to your computer and use it in GitHub Desktop.
define([
"lib/react/react"
], function(React) {
return function() {
return {
onMessageCallback: null,
init: function(message_callback) {
this.TIMEOUT = 500;
this.onMessageCallback = message_callback;
var WS_URL = this.getWebsocketUrl();
this.ws = new WebSocket(WS_URL);
this.ws.onmessage = function(e) {
this.onMessageCallback(JSON.parse(e.data));
}.bind(this);
this.ws.onopen = function(e) {
this.retry_times = 0;
}.bind(this);
this.ws.onclose = this.waitForWsConnection.bind(this);
this.ws.onerror = this.waitForWsConnection.bind(this);
return this;
},
waitForWsConnection: function(callback) {
if (this.isClosed()) {
this.retry_times++;
this.init(this.onMessageCallback);
}
if (!this.isOpen()) {
setTimeout(function () {
if (this.isOpen()) {
return callback();
} else {
this.waitForWsConnection(callback);
}
}.bind(this), this.TIMEOUT * this.retry_times);
} else {
return callback();
}
},
sendMessage: function(msg) {
this.waitForWsConnection(function() {
this.ws.send(JSON.stringify(msg));
}.bind(this));
return this;
},
isClosed: function() {
return [WebSocket.CLOSED, WebSocket.CLOSING].indexOf(this.ws.readyState) != -1;
},
isOpen: function() {
return this.ws.readyState == WebSocket.OPEN;
}
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment