2017-03-24 9 views
2

私はJavascriptが新しく、コールバックが現時点で少し気になります。 teletyperDiologue関数をコールバックにするにはどうすればよいですか?主な理由は、私は、displayOut関数が終了する前にteletyperがその仕事を終わらせたいということです。ご協力いただきありがとうございます。あなたのケースでこれをコールバック関数にするにはどうすればよいですか?

function test(a) { a(); } 
function x() { alert('hello'); } 
test(x); 

:例として

function displayOut() { 
 
\t 
 
\t // images 
 
\t document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")"; 
 
\t // Diologue box 
 
\t diologueBox.innerHTML = ""; // Clear Box 
 
\t teleTyperDiologue(db.rooms[roomLoc].description + 
 
\t \t " The room contains: " + 
 
\t \t \t (function() { 
 
\t \t \t \t let x = ""; 
 
\t \t \t \t for (let i = 0; i < db.items.length; i++) { 
 
\t \t \t \t \t if (db.items[i].location === roomLoc && db.items[i].hidden === false) { 
 
\t \t \t \t \t \t x += db.items[i].name + ", " 
 
\t \t \t \t \t } 
 
\t \t \t \t } 
 
\t \t \t \t x = x.slice(0, x.length -2); 
 
\t \t \t \t if (x === "") { 
 
\t \t \t \t \t x = " nothing of special interest"; 
 
\t \t \t \t } 
 
\t \t \t \t return x; 
 
\t \t \t })() 
 
\t \t + "."); 
 
}; 
 

 

 
// Teletyper for Diologue Box 
 
function teleTyperDiologue(string) { 
 
\t for (let i = 0; i < string.length; i++) { 
 
\t \t setTimeout(function() { 
 
\t \t \t diologueBox.innerHTML += string.slice(i, i + 1); 
 
\t \t }, 5 * i); 
 
\t } 
 
}

+1

teleTyperDiologue機能はタイマーイベントを持っているので、displayOut機能が終了した後に、それは常に実行され、あなたは「発電機」を試すことができ、現在サポートされていない機能のES6タイプです今日のブラウザでは、バーベル、タイピッチトランスパイライザでコンパイルすることができます。 –

答えて

3

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); 
2

あなたの周りの変数のように関数を渡し、関数内でそれらを返すと、それらを使用することができます他の機能ではそのため、コールバック関数を引数として別の関数に渡すと、関数定義を渡すだけで済みます。

以下の例を参照してください。

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);

+0

ありがとう、私はなぜこのような問題を抱えているのか分かりません。 – Cuckoo

関連する問題