0
new Something({
    events:{
        load: (function loopsiloop(){

            console.log(this);  // firstime this will be Something, but next call what its

            setTimeout(function(){
                console.log(this);
                $.ajax({
                    url: 'foo.htm',
                    context: this,
                    success: function( response ){
                        // do something with the response
                    },
                    error: function(){
                        // do some error handling.  you
                        // should probably adjust the timeout
                        // here.
                    },
                    complete: function(){
                        loopsiloop(); // recurse  //need to bind this here like loopsiloop().bind(this)
                    }
                });
            }.bind(this), 5000);
        }),
        click: function(){
            alert("clicked");
        }
    }

})

コードを調べてコメントを読んでください。ここで問題は関数で使用する必要があるthisためsetTimeOut、にバインドthisしてsetTimeOutいますが、関数を再帰的に呼び出すと、の値はthis同じになりません。

注意:-オブジェクトを関数に渡したくないし、使用したくないsetIntervelhttp://www.erichynds.com/javascript/a-recursive-settimeout-pattern/

4

2 に答える 2

2

再帰呼び出しは次のように記述できます。

complete: function() {
    loopsiloop.call(this);
}

コンテキストが2回目に正しく設定されていることを確認します。

このように書くこともできますが、.bindパスごとに何度も呼び出されるため、お勧めしません。

complete: loopsiloop().bind(this)  // NB: no function wrap, just passes the ref
于 2013-02-04T11:07:29.003 に答える
0

バインドしたり、使用したりしないでくださいthisvar someVariable = this;呼び出す前に設定setTimeoutし、再帰のスコープ内にとどまらせます(this関数内ではなく使用します)。

于 2013-02-04T10:59:45.747 に答える