2015-06-01 56 views
1

我有一个具有打印按钮的网页。一旦打印按钮被按下我有一个函数确定布尔值从true变为false的时间

function pWindowNeeded() { 
    if (newPWindowNeeded == 'Y') { 
     return true; 
    } 
    return false; 
} 

以后,我要打印的说,如果这是真的,那么打开含有PDF的新窗口另一个函数,改变newPWindowNeeded以“N”

这一切工作正常。

此外,当用户点击打印窗口,现在我有这个功能正在运行

function alertWindow() 
{ 
    var w = window.open('','',' width = 200, height = 200, top = 250 , left = 500 '); 
    w.document.write("Please Wait<br> Creating Document(s).<br><img src='loadingimage.gif'>"); 
    w.focus(); 
    setTimeout(function() {w.close();}, 5000); 
} 

这也能正常工作,创建窗口,然后在5秒后自动关闭。

这适用于现在正常工作,但我真正需要的是评估何时pWindowNeeded返回false,何时返回false我需要它自动关闭窗口。

评估pWindowNeeded从真变为假时最有效的方法是什么?

感谢

+0

难道你不能只是再次检查'newPWindowNeeded'吗?或者设置另一个标志? – JJJ

+1

最好的方法是在使用消息总线设置“pWindowNeeded”时触发事件。穷人的方式是有一个'setTimeout'不断运行并检查'pWindowNeeded'的值 –

+0

出于好奇,什么代码将'newPWindowNeeded'改为'Y'?看起来像是一种奇怪的方式来触发窗口打开。 – Katana314

回答

1

效率最低,最简单的方式做到这一点是轮询使用setTimeout的价值。

function callbackWhenWindowNotNeeded(cb) { 
    if (!pWindowNeeded()) { 
     cb(); 
    } else { 
     // The lower the number, the faster the feedback, but the more 
     // you hog the system 
     setTimeout(callbackWhenWindowNotNeeded, 100); 
    } 
} 

function alertWindow() { 
    var w = window.open('','',' width = 200, height = 200, top = 250 , left = 500 '); 
    w.document.write("Please Wait<br> Creating Document(s).<br><img src='loadingimage.gif'>"); 
    w.focus(); 

    callBackWhenWindowNotNeeded(function() { 
     w.close(); 
    }); 
} 

理想情况下,您会使用某种MessageBus来阻止轮询。这是一个穷人巴士的例子。

var MessageBus = (function(){ 
    var listeners = []; 
    return { 
    subscribe: function(cb) { 
     listeners.push(cb); 
    }, 
    fire: function(message) { 
     listeners.forEach(function(listener){ 
      listener.call(window); 
     }); 
    } 
})(); 

function alertWindow() { 
    var w = window.open('','',' width = 200, height = 200, top = 250 , left = 500 '); 
    w.document.write("Please Wait<br> Creating Document(s).<br><img src='loadingimage.gif'>"); 
    w.focus(); 

    MessageBus.subscribe(function(message, event) { 
     if (message == 'WINDOW_NOT_NEEDED') { 
      w.close(); 
     } 
    }); 
} 

// Then wherever you set your newPWindowNeeded 
newPWindowNeeded = 'N'; 
MessageBus.fire('WINDOW_NOT_NEEDED'); 
+0

非常感谢! – JOO

+0

@JOO如果能解决您的问题,请接受答案。尝试'MessageBus'方法,使用类似http://robdodson.me/javascript-design-patterns-observer/ –

+0

我将尝试使用MessageBus。我有一个try catch来检查是否启用了弹出窗口拦截器,并且由于某种原因它正在触发该捕获。我会回到你的结果 – JOO

相关问题