I have a piece of code that works well but I cannot get the idea behind part of it, so any help is appreciated.
In the following function what does the bind(this) function do at the end of code? I have searched a lot both SO and JQuery documentation but couldn’t find any usage like that. All usages of bind() try to hook up a function to an event but here bind is called after a function and passed a JQuery object (which is an img tag in this case). Thanks in advance.
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));
});
});
}
bindcreates a new function which, when invoked, has itsthisvalue set to the first argument passed. So in this case, theanimatecallback will have its context set tosrcDom.eq(0)when invoked.More on this here