I have a web-app that polls for data periodically to 3rd party services (say Facebook, Twitter, and so on). This poll/request is made via JSONP (to avoid cross-domain issue).
For example, a simple request would be something like this:
function jsonp_callback() {
// Do something
}
var url = 'http://some.service.com/getresult?callback=jsonp_callback';
$http.jsonp(url);
However since there can be another type of request that can be made at any given time (for example: to send or post an update), I created a wrapper to handle the callbacks.
The implementation is something 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);
If you notice, after some time, the myCb.fn will be bloated will callbacks that were old or have already executed. Mu question is, do I need to create a mechanism to garbage-collect those who have been executed and no longer needed?
You don't necessarily need to remove old callbacks, if you will only make a few calls per page, but if your page is a long running one and makes calls repeatedly it could be a good idea to delete them.
The "mechanism" could be as simple as
delete self.fn[id];
after calling the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With