4 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
8 (function (exports, io, global) {
14 exports['xhr-polling'] = XHRPolling;
17 * The XHR-polling transport uses long polling XHR requests to create a
18 * "persistent" connection with the server.
24 function XHRPolling () {
25 io.Transport.XHR.apply(this, arguments);
29 * Inherits from XHR transport.
32 io.util.inherit(XHRPolling, io.Transport.XHR);
35 * Merge the properties from XHR transport
38 io.util.merge(XHRPolling, io.Transport.XHR);
46 XHRPolling.prototype.name = 'xhr-polling';
49 * Indicates whether heartbeats is enabled for this transport
54 XHRPolling.prototype.heartbeats = function () {
59 * Establish a connection, for iPhone and Android this will be done once the page
62 * @returns {Transport} Chaining.
66 XHRPolling.prototype.open = function () {
69 io.Transport.XHR.prototype.open.call(self);
74 * Starts a XHR request to wait for incoming messages.
81 XHRPolling.prototype.get = function () {
82 if (!this.isOpen) return;
86 function stateChange () {
87 if (this.readyState == 4) {
88 this.onreadystatechange = empty;
90 if (this.status == 200) {
91 self.onData(this.responseText);
101 this.onerror = empty;
102 self.retryCounter = 1;
103 self.onData(this.responseText);
107 function onerror () {
108 self.retryCounter ++;
109 if(!self.retryCounter || self.retryCounter > 3) {
116 this.xhr = this.request();
118 if (global.XDomainRequest && this.xhr instanceof XDomainRequest) {
119 this.xhr.onload = onload;
120 this.xhr.onerror = onerror;
122 this.xhr.onreadystatechange = stateChange;
129 * Handle the unclean close behavior.
134 XHRPolling.prototype.onClose = function () {
135 io.Transport.XHR.prototype.onClose.call(this);
138 this.xhr.onreadystatechange = this.xhr.onload = this.xhr.onerror = empty;
147 * Webkit based browsers show a infinit spinner when you start a XHR request
148 * before the browsers onload event is called so we need to defer opening of
149 * the transport until the onload event is called. Wrapping the cb in our
150 * defer method solve this.
152 * @param {Socket} socket The socket instance that needs a transport
153 * @param {Function} fn The callback
157 XHRPolling.prototype.ready = function (socket, fn) {
160 io.util.defer(function () {
166 * Add the transport to your public io.transports array.
171 io.transports.push('xhr-polling');
174 'undefined' != typeof io ? io.Transport : module.exports
175 , 'undefined' != typeof io ? io : module.parent.exports