0

私はうまく機能するコードを持っていますが、その一部の背後にあるアイデアを得ることができないので、助けていただければ幸いです。

次の関数では、bind(this)関数はコードの最後で何をしますか? SO と JQuery の両方のドキュメントをたくさん検索しましたが、そのような使用法は見つかりませんでした。bind()関数をイベントにフックしようとするすべての使用法ですが、ここでは関数の後に 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));
        });
    });
}
4

1 に答える 1

0

bindthis呼び出されると、渡された最初の引数に値が設定される新しい関数を作成します。したがって、この場合、コールバックは呼び出されたときに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)*/

    });

詳細はこちら

于 2012-12-06T10:37:48.197 に答える