messenger.js 1.95 KB
define([], function() {
    var listeners = [];
    var messenger = {
        process: function() {
            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.onreadystatechange) {
                            request.onreadystatechange = null;
                        }
                        if (request.responseText) {
                            var newText = request.responseText.substr(responseLength);
                            if (newText.length > 0) {
                                for (var i=0; i < listeners.length; i++) {
                                   listeners[i](newText); 
                                }
                            }
                            responseLength = request.responseText.length;
                        }
                    }
                    if (request.readyState == 4) {
                        if (request.status == 200) {
                            messenger.process();
                        } else {
                            console.log('Error, retrying in 5 seconds');
                            setTimeout(function() { messenger.process(); }, 5000);
                        }
                    }
                }
            };
            request.send(null);
        },
        addListener: function(listener) {
            listeners.push(listener);
        },
        removeListener: function(listener) {
            var index = listeners.indexOf(listener);
            if (index > -1) {
                array.splice(index, 1);
            }
        }
    }
    messenger.process();

    return messenger;
});