簡體   English   中英

暫停一個函數並等待另一個函數執行

[英]pause a function and wait for another function to execute

這是我的情況,我有三個功能

第一個是主函數,這也調用第二個函數以獲取值。

這是第一個電話

this.markdownarea.on("click", "a[data-markdownarea-act]", function(){

//now open a modal window where user will upload a image and get a link
$("#modal-imgupload-content, #modal-bg-imgupload").toggleClass("active");

// now we need the url, so we call the second function to fetch it
var img_up_url = get_img_link();

if(img_up_url){
// now do some thing crazy here ...
}
});

我在第一個函數(上面)中添加了注釋,因此它應該解釋該腳本的作用。

現在第二個功能:

function get_img_link() {
// pause this function immediately and let the user runs the third function 
//manually so the value will assign to val and then resume it.
alert(val);
return val;
}

第三個功能僅在用戶單擊提交按鈕時才起作用。 在第三個函數執行之后,它為第二個函數定義了val變量的值。

function get_img_url(){

//now when the user click the submit this will get the value of the input field
var e = document.getElementsByName('link_img_up')[0];
val = e.value;
//okay now the value is assigned and the second function should resume 
}

問題是,當用戶運行第一個功能時,將打開一個模態窗口,用戶可以獲取一個值,然后單擊提交按鈕,該按鈕將運行第三個功能並為val分配值,第二個選項應立即恢復,但應改為它立即執行第二個,返回undefined variable val

所以我希望第二個功能暫停直到用戶運行第三個功能並為val分配一個值

我不知道這樣做的方法! 有沒有更好的選擇

由於您只是返回get_img_link()的值, get_img_link()刪除該函數

並修改您的get_img_url()以返回該值。

function get_img_url(){

//now when the user click the submit this will get the value of the input field
var e = document.getElementsByName('link_img_up')[0];
val = e.value; 
return val;
//okay now the value is assigned and the second function should resume 
}

恐怕您必須將要暫停的動作分為兩個部分。

創建一個對象,該對象使用對用戶完成選擇后要執行的操作的回調進行初始化。 給該對象一個在交互部分完成后應調用的方法。 將對象傳遞給交互方法。

mySelection = $(...);

// now we need the url, so we call the second function to fetch it
get_img_link( function ( img_up_url ) {
  if( img_up_url ) {
    // now do some thing crazy here ...
    mySelection.doSomethingWithImageUpUrl(...)
  } 
});

第二個對話框獲取img_up_url,然后調用回調函數,該函數在其關閉時具有初始選擇。 就個人而言,更喜歡使用MVCish方法,而不是綁定到DOM元素的回調級聯。

我認為您希望用戶首先輸入,然后執行其余代碼,這可能是您想要的:

對於用戶輸入的模式窗口,我們想先將其命名為assaign,然后執行其余代碼,

$("#modal-imgupload_on").click(function () {
        function lol(){
        $("#modal-imgupload-content, #modal-bg-imgupload").toggleClass("active");
        }
        lol();
        });

現在我們要執行其余代碼,而不是暫停。

            $("#img_up_sub").click(function () {
            var e = document.getElementsByName('link_img_up')[0];
            val = e.value;
            var img_up_url = val;
            if(img_up_url){
            var img_edit_process = function(editor){
            //do something crazy here
            };

             //want some function to execute after .....

            }
            $("#modal-imgupload-content, #modal-bg-imgupload").toggleClass("active");
            //now close the modal and reset all the value
        });

希望這可以幫助 :)

暫無
暫無

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

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