2016-08-21 91 views
0

所以我想在.fadeOut()完成動畫後使用回調函數。我可以用下面的方法成功地做到這一點,沒問題。工作就像我想(HTML和CSS只是一個單一的黑色方形格)jQuery與回調和完成

function fadeOutThing(speed, callback) { 
    $('div').parent().fadeOut(speed, function() { 
     if (typeof callback === "function") { 
     callback(); 
     } 
    }); 
} 

function OtherThing() { 
    console.log("hello"); 
} 

fadeOutThing(5000, OtherThing); 

我真正想要的是該回調函數有自己的說法,這可能是另一個回調函數,如下所示。問題是,當我這樣做,日誌將顯示之前的動畫完成:Here's the fiddle

function fadeOutThing(speed, callback) { 
    $('div').parent().fadeOut(speed, function() { 
     if (typeof callback === "function") { 
     callback(); 
     } 
    }); 
} 

function OtherThing(stuff) { 
    console.log("hello" + stuff); //This displays too soon! 
} 

fadeOutThing(5000, OtherThing(' stuffsss')); 

這究竟是爲什麼?我不瞭解什麼?

回答

1

問題是因爲您在加載頁面時立即致電OtherThing()。這意味着您將結果OtherThing()函數作爲回調參數,而不是參考函數。

要做到你需要什麼,你可以提供一個匿名函數,它包裝的OtherThing()調用回調:

fadeOutThing(5000, function() { 
    OtherThing(' stuffsss')); 
}); 
0

綁定的參數,而不是調用函數如下:

fadeOutThing(5000, OtherThing.bind(this,' stuffsss')); 
0

你在屬性中使用/調用函數,所以而不是函數聲明你發送它的返回在這種情況下是沒有回報所以:

fadeOutThing(5000, OtherThing(' stuffsss')); 

等於

fadeOutThing(5000, notDeclaredNothing); //undefined variable 

要發送函數的聲明,並設置PARAMATERS例如,您可以第三paramater做:

function fadeOutThing(speed, callback,attrs) { 
    $('div').parent().fadeOut(speed, function() { 
     if (typeof callback === "function") { 
     callback(attrs); //use with attributes 
     } 
    }); 
} 

用法:

fadeOutThing(5000, OtherThing,'stuffsss'); 

或第二選擇是使用綁定 - 綁定創建新的功能給定這個和給定的屬性:

fadeOutThing(5000, OtherThing.bind(this,'stuffsss')); 

這在全局範圍內是窗口對象。