function Service(socket) {
this.socket = socket;
this.liveStreams = {};
this.pendingSubscribe = [];
socket.on('response', function (str) {
/* Assume response is a stringified json object, e.g.
{
pair:'NewYork-London',
update: "whatever goes here"
}
*/
var data = JSON.parse(str);
this.liveStreams[data.pair].call(null, data.update);
}.bind(this));
}
Service.prototype.flush = function () {
display('flusing request ' + JSON.stringify(this.pendingSubscribe));
this.socket.emit('request', this.pendingSubscribe);
// reset for next flushSubscribe
this.pendingSubscribe = [];
}
Service.prototype.subscribe = function (pair, callback) {
/* in case of intial page load, this "deferring" will force batching */
if (this.pendingSubscribe.length === 0) setTimeout(this.flush.bind(this), 0);
this.pendingSubscribe.push(pair);
this.liveStreams[pair] = callback;
};
/* other methods, e.g unsubscribe etc. */
/*Let's fake socket.io and do a test below*/
function display ( stuff ) {
$('#output').append('<pre>' + stuff + '</pre>');
}
var fakeSocket = {
on: function (subject, callback) {
this.callback = callback;
},
emit: function (subject, string_array) {
var self = this;
string_array.forEach( function (pair) {
var response = { pair: pair, update:'UPDATES of ' + pair };
setTimeout( self.callback, 1000, JSON.stringify(response));
});
}
};
var service = new Service(fakeSocket);
display('... Subscribing to CT-VT');
service.subscribe('CT-VT', function (x) {
display('... CT-VT --response--> ' + JSON.stringify(x));
});
setTimeout( function () {
display('\nNext we will make a number of subscribe calls from a loop\nbut the request should be batched due to setTemout(..,0)');
var choices = ['NY-LN', 'LN-NY', 'NY-LA', 'LA-NY'];
choices.forEach(function (choice) {
display('... Subscribing to...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!