2015-06-01 59 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

相關問題