我有一个 web 应用程序,它作为托管在单个父窗口(基本上是修改后的 GWT)http://en.wikipedia.org/wiki/Google_Web_Toolkit中的多个 iframe 运行。我试图让它们通过使用 window.parent 全局对象共享数据服务,而不是每个 iframe 单独访问我们的后端服务。我设置了这个单例模式-
define(function(){
var DocumentService = function () {
//create namespace if not there
if (!parent.OurApp) {
parent.OurApp= {};
}
//grab the singleton instance and return it if there
if (parent.OurApp.DocumentService) {
return parent.OurApp.DocumentService;
}
//assign the global
parent.OurApp.DocumentService= this;
//start fetch on instantiation
this.items;
this.getItems();
this.startInterval();
}
DocumentService.prototype.getItems = function(){
//Rest service call 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();
});
所以这个过程在初始加载时起作用,getItems() 从服务加载数据,setInterval 启动一个循环来运行 getItems。我可以查看 items 数组并查看更改和添加。
所以现在这就是棘手的地方。如果您通过右键单击“重新加载框架”单独重新加载框架,而不是父窗口,则服务的父实例继续运行,但是当 iFrame 通过获取新的 DocumentService() 访问“父”实例单例时,线程不再同步或其他什么,因为框架不再注册控制台日志或更改项目数组。有什么理由解释为什么会发生这种情况?我的单例模式有缺陷吗?