Last active
August 29, 2015 14:08
-
-
Save adoc/6baf70e56153f88575da to your computer and use it in GitHub Desktop.
socketRequest: Mimics a very simple Request/Response dynamic through a socket.
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
/* Mimics a very simple Request/Response dynamic through a | |
socket. | |
see `bicycle_path.views.EnabledNamespace` for an example of | |
the server-side component. | |
*/ | |
function socketRequest(socket, method, data, options) { | |
data || (data = {}); | |
options || (options = {}); | |
options.timeout || (options.timeout = 10000); | |
options.success || (options.success = function () {}); | |
options.timeoutFail || (options.timeoutFail = function() { | |
throw "'socketRequest' expected a response "; | |
}); | |
var self = this, | |
syncId = _.uniqueId(method), | |
timeoutTimer = setTimeout(options.timeoutFail, options.timeout); | |
socket.once("response_"+syncId, function(responseData) { | |
clearTimeout(timeoutTimer); | |
options.success(responseData); | |
}); | |
// Send the command through the socket. | |
socket.emit(method, _.extend({ | |
request_id: syncId, | |
}, data)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment