2012-12-06 36 views
0

我有一段代碼運行良好,但是我無法得到它的部分背後的想法,所以任何幫助表示讚賞。在函數後調用JQuery.bind()

在下面的函數中,函數在代碼的末尾做了什麼?我搜索了很多SO和JQuery文檔,但找不到像這樣的用法。 bind()的所有用法都嘗試將一個函數連接到一個事件,但是這裏的綁定是在一個函數之後調用的,並且傳遞了一個JQuery對象(在這種情況下是一個img標籤)。提前致謝。

function refreshCaptcha() { 
    var currCaptcha = $('#captcha-div img'); 

    currCaptcha.animate({ 
     opacity: 0.3 
    }, 300); 

    $.getJSON("/captcha.json", function (data) { 
     var src = $("#captcha-template").html(); 
     var template = Handlebars.compile(src); 
     var newSrc = template(data); 
     var srcDom = $(newSrc); 

     srcDom.eq(0).css('opacity', 0).load(function() { 

      currCaptcha.animate({ 
       opacity: 0 
      }, 250, function() { 
       $("#captcha-div").html(srcDom); 

       $(this).animate({ 
        opacity: 1 
       }, 250); 

      }.bind(this)); 
     }); 
    }); 
} 
+0

我測試過自己,但我不能讓的意思,我的意思是不正是這段代碼做。我想知道這裏使用了bind()的哪個重載。 –

+0

它不是'jQuery.bind()',它是標準的Javascript bind()。見阿薩德的答案。 – Barmar

回答

0

bind創建一個新的函數,調用時,有其this值設置爲傳遞的第一個參數。因此,在這種情況下,animate回調將在調用時將其上下文設置爲srcDom.eq(0)

srcDom.eq(0).css('opacity', 0).load(function() { 

     // In here, the value of "this" is srcDom.eq(0) 

     currCaptcha.animate({ 
      opacity: 0 
     }, 250, function() { 
      $("#captcha-div").html(srcDom); 

      $(this).animate({ 
       opacity: 1 
      }, 250); 

     }.bind(this)); /*When that callback is invoked, all 
         occurrences of "this" inside it will refer 
         to srcDom.eq(0)*/ 

    }); 

更多關於此here

+0

所以這不是JQuery的綁定,但JavaScript的? –

+0

@JavadAmiri是的。 –