Created
March 10, 2015 11:53
-
-
Save beshur/d031ebd9ccaac5e1e4c7 to your computer and use it in GitHub Desktop.
socket helper
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
var socketHelper = function() { | |
this.clientId = ""; | |
this.getClientId = function() { | |
return this.clientId; | |
} | |
this.address = "localhost"; | |
this.socket = new WebSocket(this.address); | |
/** Keep messages in queue until socket connection is established */ | |
this.deferredMessages = []; | |
this.deferredMessagesRun = function() { | |
console.log("--- - deferredMessagesRun"); | |
if (this.deferredMessages.length > 0) { | |
this.deferredMessages.forEach(function(id) { | |
var shift = this.deferredMessages.shift(); | |
console.log("SHIFT", shift); | |
var item = this.journalGet(shift); | |
console.log(item); | |
this.sendMessage(item); | |
}, this); | |
} | |
} | |
/** General message sending */ | |
this.sendMessage = function(message, cb, context) { | |
if (message) { | |
message.id = this.getClientId() + "%%" + Date.now(); | |
} | |
if (typeof cb !== "function") { | |
cb = false; | |
} | |
this.journalAdd(message, cb, context); | |
if (this.socket.readyState === 1) { | |
message = JSON.stringify(message); | |
this.socket.send(message); | |
$(".b_notifyze_loading").fadeIn("fast"); | |
} else { | |
console.log('Defer message', message.id); | |
this.deferredMessages.push(message.id); | |
} | |
} | |
this.journal = {'_timer': {}};; | |
/** Journal clear */ | |
this.journalClear = function() { | |
// cleared on connection restart | |
this.journal = {'_timer': {}}; | |
return true; | |
} | |
/** Journal Add */ | |
this.journalAdd = function(message, cb, context) { | |
var _this = this; | |
this.journal[message.id] = message; | |
if (typeof cb === "function") { | |
this.journal[message.id + '_cb'] = cb; | |
if (typeof context != "undefined") { | |
this.journal[message.id + '_cb_context'] = context; | |
} | |
} | |
} | |
/** Journal item getter */ | |
this.journalGet = function(messageId) { | |
return this.journal[messageId]; | |
} | |
return this; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment