My web-app regularly polls 3rd party services (such as Facebook and Twitter) for data using JSONP to avoid cross-domain issues.
Here is an example of a simple request:
function jsonp_callback() {
// Do something
}
var url = 'http://some.service.com/getresult?callback=jsonp_callback';
$http.jsonp(url);
In order to handle various types of requests that may occur at any time (e.g., sending or posting updates), I developed a wrapper for managing callbacks.
The implementation looks like this:
// Callback handler
var myCb = (function() {
var F = function() {};
F.prototype.fn = {};
F.prototype.create = function(fn, scope) {
var self = this;
var id = new Date().getTime();
self.fn[id] = function() {
if (typeof fn === 'function') {
fn.call(scope);
}
}
return 'myCb.fn.' + id;
}
return new F();
})();
// JSONP request
var cb = myCb.create(function() {
// Do something
});
var url = 'http://some.service.com/getresult?callback=' + cb;
$http.jsonp(url);
As time passes, the myCb.fn object may become bloated with executed or obsolete callbacks. Should I implement a mechanism to clean up these unnecessary callbacks?