2012-06-13 70 views
0

所以我們可以說我打電話,像這樣的功能:使用Javascript - 使功能告訴來電者,當函數執行完畢

some_function('pages',{attr1: 1, attr2: 2},function(){ 
    alert('the function is ready!'); 
} 

現在我該怎樣建立「some_function()」函數,以便返回呼叫者已準備好並使警報熄滅?

謝謝:)

+2

...你在這做什麼? – Sebas

+0

你的意思是像jQuery? –

+0

很難理解你的意思,但也許你想在第一個回調完成時觸發第二個回調* – apsillers

回答

1

我認爲你的意思是回調。 也許是這樣的:

function some_function(param1, param2, callback) { 

    // normal code here... 

    if (typeof callback === 'function') { // make sure it is a function or it will throw an error 
     callback(); 
    } 
} 

用法:

some_function("hi", "hello", function() { 
    alert("Done!"); 
}); 
/* This will do whatever your function needs to do and then, 
when it is finished, alert "Done!" */ 

注:把你的if條款return後。

1

你的意思是這樣的嗎?

function some_function(type, options, callback) { 
    if (some_condition) { 
    callback(); 
    } 
} 
+0

如果它們沒有指定回調會引發錯誤。 –

+0

你是什麼意思some_condition。會是什麼呢? –

+0

@AnishGupta我知道它會拋出錯誤...「some_condition」意味着任何表達式評估結果爲真。 – ioseb

1

承擔some_function簽名看起來是這樣的:

function some_function(name, data, callback) 

你只需要調用callback當你準備好。

function some_function(name, data, callback){ 
    // do whatever 
    if(typeof callback === 'function'){ 
     callback(); // call when ready 
    } 
} 
+0

如何啓動我在調用函數時指定的回調?或者你的例子已經這樣做了? –

+0

你是什麼意思的「發起回調」?我的例子將調用作爲回調傳遞的函數。您只需要將該if語句放在方法的正確位置即可。 –

相關問題