JSFiddle - React, Tailwind, and code Playground

by ustamansangat

HTML

<div id='output' />

JavaScript

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...