messenger.js 2.6 KB
define([], function() {
    var channels = {};
    var messenger = {
        process: function() {
            var self = this;
            var url = "/comet/messenger"
            var request =  new XMLHttpRequest();
            var responseLength = 0;
            request.open("GET", url, true);
            request.setRequestHeader("Content-Type","application/x-javascript;");
            request.onreadystatechange = function() {
                if (request.readyState == 3 || request.readyState == 4) {
                    if (request.status == 200){
                        if (request.responseText) {
                            var newText = request.responseText.substr(responseLength);
                            if (newText.length > 0) {
                                self.deliver(newText);
                            }
                            responseLength = request.responseText.length;
                        }
                    }
                    if (request.readyState == 4) {
                        // Request is complete. Remove existing callback.
                        request.onreadystatechange = null;
                        if (request.status == 200) {
                            setTimeout(function() { messenger.process(); }, 500);
                        } else {
                            console.log('Error, retrying in 5 seconds');
                            setTimeout(function() { messenger.process(); }, 5000);
                        }
                    }
                }
            };
            request.send(null);
        },
        deliver: function(newText) {
            try {
                var json = JSON.parse(newText);

                if (json.channel && channels[json.channel]) {
                    for (var i=0; i < channels[json.channel].length; i++) {
                       channels[json.channel][i](json); 
                    }
                }
            } catch (err) {
                console.log('Error processing COMETd message', newText, err);
            }
        },
        addListener: function(listener) {
            this.addListener('ALL', listener);
        },
        addListener: function(channel, listener) {
            if (!channels[channel]) {
                channels[channel] = [];
            }
            channels[channel].push(listener);
        },
        removeListener: function(listener) {
            this.removeListener('ALL', listener);
        },
        removeListener: function(channel, listener) {
            console.log('Remove listener from channel', listener, channel);
        }
    }
    messenger.process();

    return messenger;
});