簡體   English   中英

javascript等待某件事變為真實

[英]javascript WAIT for something to be true

我在javascript函數中創建一個原型窗口。 在窗口中,我加載了一個用戶必須在其中選擇內容的站點。 我希望javascript函數能夠等到用戶選擇了某些內容,然后返回用戶選擇的內容的值。

function showTargetDirectoryChooser(){
  var win = new Window( 'dirchooser_' + new Date().getTime() , {className: 'alphacube', width: 320, height: 470, url: '/directories/choose', maximizable: false});
  win.showCenter();
  win.setDestroyOnClose();

  // WAIT_UNTIL( win.content.contentWindow.Directory != null )

  return win.content.contentWindow.Directory
}

我在這里找到了可能可以使用的東西-但我不知道該如何...

這是一個異步過程。 最好通過回調來處理。

例如,您不能使用closeCallback嗎?

function showTargetDirectoryChooser(done){
  var win = new Window( 'dirchooser_' + new Date().getTime() , {className: 'alphacube', width: 320, height: 470, url: '/directories/choose', maximizable: false});
  win.showCenter();
  win.setDestroyOnClose();

  // This will ensure 
  win.setCloseCallback(function () {
      done(win.content.contentWindow.Directory);
      return true; // or return false if you don't want the window to be closed
  });

  return true;
}

有了這個,你會改變

var chosenDir = showTargetDirectoryChooser();
// do something with chosen directory

進入

var chosenDir;
showTargetDirectoryChooser(function (directory) {
    chosenDir = directory;
    // do something with the chosen directory
});

一種選擇是使用事件處理程序。 Directory通過點擊或者一個變更事件,如果被解雇,附加處理這需要該事件,並將它返回到你的主窗口的功能。 這將需要使您的代碼異步-這樣您就擁有了一個調用showTargetDirectoryChooser()的調用者和一個將目錄結果作為單獨函數的回調。 不過,在這里重新構建代碼並將其分解為調用方和回調並不應該太復雜。

您還可以使用setTimeout並輪詢win.content.contentWindow.Directory的內容, win.content.contentWindow.Directory所示:

function showTargetDirectoryChooser(){
  var win = new Window( 'dirchooser_' + new Date().getTime() , {className: 'alphacube', width: 320, height: 470, url: '/directories/choose', maximizable: false});
  win.showCenter();
  win.setDestroyOnClose();

  setTimeout("pollDirectory()", 500); // poll in a half second
}

function pollDirectory() {
  if(win.content.contentWindow.Directory != null) {
    callback(win.content.contentWindow.Directory); // you will need an asynch callback
  } else {
    setTimeout("pollDirectory()", 500); // poll in a half second
  }

}

這樣做還需要您的代碼是異步的。

另一種選擇是查看jquery wait ,但這是超時而不是在條件上等待。 或有一組JS反應式擴展 ,但這似乎對您的工作有些過大。 不過,可觀察性的概念可能是您要研究的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM