I have developed a web application that runs on multiple iframes within a parent window, similar to a modified version of GWT. Rather than each individual iframe accessing our backend service separately, I am attempting to have them share the data service through the use of the window.parent global object. I have implemented a singleton pattern for this purpose-
define(function(){
var DocumentService = function () {
//create namespace if it doesn't exist
if (!parent.OurApp) {
parent.OurApp= {};
}
//returning the singleton instance if already present
if (parent.OurApp.DocumentService) {
return parent.OurApp.DocumentService;
}
//assign the global instance
parent.OurApp.DocumentService = this;
//start fetching data upon instantiation
this.items;
this.getItems();
this.startInterval();
}
DocumentService.prototype.getItems = function(){
//Call to Rest service here
//this.items.push(response); some pseudo-code here
};
DocumentService.prototype.startInterval = function(){
var self = this;
this.intervalId = parent.setInterval(function(){
console.log("Fetching items @ " +new Date());
this.getItems();
},300000);
};
//return new instance or singleton instance
return new DocumentService();
});
This process works fine on initial load - getItems() loads data from the service and setInterval initiates a loop to run getItems at regular intervals. The changes to the items array can be monitored and tracked.
The challenge arises when an iframe is individually reloaded by right-clicking and selecting "reload frame", without refreshing the parent window. In this scenario, while the parent instantiation of the service continues to run, the threads seem to go out of sync when the iframe accesses the "parent" instance singleton by obtaining a new DocumentService(). This results in the frame no longer displaying console logs or reflecting changes in the items array. Any insights into why this occurs? Is there a flaw in my singleton pattern?