如何将其转换为回调函数?

时间:2017-03-24 12:55:30

标签: javascript callback

我是Javascript的新手,而且回调现在让我大吃一惊。如何将teletyperDiologue功能转换为回调?主要原因是我希望teletyper在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);
	}
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

举个例子:

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

答案 1 :(得分:2)

您可以像变量一样传递函数并将它们返回到函数中,并在其他函数中使用它们。因此,当您将回调函数作为参数传递给另一个函数时,您只需要传递函数定义。

见下面的例子。

&#13;
&#13;
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);
&#13;
&#13;
&#13;