[英]How do I turn this into a callback function?
我是Java的新手,而回調在此刻讓我有些驚訝。 如何將teletyperDiologue函數轉換為回調? 主要原因是我希望電傳打字機在displayOut功能完成之前完成其工作。 預先感謝您的幫助。
function displayOut() { // images document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")"; // Diologue box diologueBox.innerHTML = ""; // Clear Box teleTyperDiologue(db.rooms[roomLoc].description + " The room contains: " + (function() { let x = ""; for (let i = 0; i < db.items.length; i++) { if (db.items[i].location === roomLoc && db.items[i].hidden === false) { x += db.items[i].name + ", " } } x = x.slice(0, x.length -2); if (x === "") { x = " nothing of special interest"; } return x; })() + "."); }; // Teletyper for Diologue Box function teleTyperDiologue(string) { for (let i = 0; i < string.length; i++) { setTimeout(function() { diologueBox.innerHTML += string.slice(i, i + 1); }, 5 * i); } }
舉個例子:
function test(a) { a(); }
function x() { alert('hello'); }
test(x);
在您的情況下:
function displayOut(callback) {
// images
document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")";
// Diologue box
diologueBox.innerHTML = ""; // Clear Box
callback(db.rooms[roomLoc].description +
" The room contains: " +
(function() {
let x = "";
for (let i = 0; i < db.items.length; i++) {
if (db.items[i].location === roomLoc && db.items[i].hidden === false) {
x += db.items[i].name + ", "
}
}
x = x.slice(0, x.length -2);
if (x === "") {
x = " nothing of special interest";
}
return x;
})()
+ ".");
};
displayOut(teleTyperDiologue);
您可以像傳遞變量一樣傳遞函數,並在函數中返回它們並在其他函數中使用它們。 因此,當您將回調函數作為參數傳遞給另一個函數時,只需要傳遞函數定義即可。
請參見下面的示例。
function displayOut() { console.log("Display Out running..."); } function teleTyperDiologue(stringParam, callback) { console.log("Running teleTyper with string param passed of: ", stringParam); callback(); } teleTyperDiologue ("Test string", displayOut);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.