Skip to content

Instantly share code, notes, and snippets.

@adoc
Last active August 29, 2015 14:08
Show Gist options
  • Save adoc/6baf70e56153f88575da to your computer and use it in GitHub Desktop.
Save adoc/6baf70e56153f88575da to your computer and use it in GitHub Desktop.
socketRequest: Mimics a very simple Request/Response dynamic through a socket.
/* 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