2012-12-06 58 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是的。 –