Created
November 15, 2009 21:59
-
-
Save tritonrc/235502 to your computer and use it in GitHub Desktop.
Javascript XPCOM Long-poll Singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); | |
var gLongPollInstance = null; | |
function LongPoll() { | |
if(gLongPollInstance) | |
return gLongPollInstance; | |
gLongPollInstance = this; | |
this.wrappedJSObject = this; | |
this.observerService = | |
Components.classes["@mozilla.org/observer-service;1"] | |
.getService(Components.interfaces.nsIObserverService); | |
this.timer = null; | |
this.endpoint = "http://notifications.example.com"; | |
this.currentRequest = | |
Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] | |
.createInstance(Components.interfaces.nsIXMLHttpRequest); | |
this.currentRequest.mozBackgroundRequest = true; | |
this.currentRequest.onreadystatechange = function(evt) { | |
if (gLongPollInstance.currentRequest.readyState == 4) { | |
var status = gLongPollInstance.currentRequest.status; | |
var timeout = 5000; | |
if(status >= 200 && status < 300) { | |
gLongPollInstance.observerService.notifyObservers( | |
null, | |
'longpoll', | |
'{"topic":"notification", "data":' + gLongPollInstance.currentRequest.responseText +'}'); | |
} else { | |
timeout = 60000; | |
} | |
gLongPollInstance.timer = | |
Components.classes["@mozilla.org/timer;1"] | |
.createInstance(Components.interfaces.nsITimer); | |
gLongPollInstance.timer.init( | |
gLongPollInstance, | |
timeout, | |
Components.interfaces.nsITimer.TYPE_ONE_SHOT); | |
} | |
}; | |
} | |
LongPoll.prototype = { | |
classDescription: "Long-Poll Component", | |
classID: Components.ID("{1C0E8E86-A661-40D0-AE3D-ABCDEFABCDEF}"), | |
contractID: "@example.com/longpoll;1", | |
QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsISupports]), | |
setEndpoint: function(nPoint) { | |
this.endpoint = nDomain; | |
this.currentRequest.abort(); | |
}, | |
poll: function() { | |
this.currentRequest.open('GET', this.endpoint, true); | |
this.currentRequest.send(null); | |
}, | |
observe: function(subject, topic, data) { | |
switch(topic) { | |
case 'timer-callback': | |
this.poll(); | |
break; | |
} | |
} | |
}; | |
var components = [LongPoll]; | |
function NSGetModule(compMgr, fileSpec) { | |
return XPCOMUtils.generateModule(components); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
classID: Components.ID("{e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8}