0

this.moveCursorBackbone で使用しようとしていますが、 I のときにundefinedconsole.logと表示されます。メソッドは明らかに定義されているため、ここで何が問題なのかわかりません。

最初はthis.switchステートメントが返されないためだと思いました。

ただし、ステートメントのconsole.log外に出ても同じです。switch

誰でも助けることができますか?

setup: function(){      
        $(document).on('keydown', this.keyCode);
},

keyCode: function(e){
                switch(e.keyCode) {
                    case 37:  console.log(this.moveCursor(-1,0)); break; //undefined
                    case 38:  return this.moveCursor(0,-1); break;
                    case 39:  return this.moveCursor(1,0); break;
                    case 40:  return this.moveCursor(0,1); break;
                    case 32:  return play.selectBlock(); break;
                    case 13:  return play.selectBlock(); break;
                };

        console.log(this.moveCursor()); //undefined
            }, 



   moveCursor: function(x, y){
                    var cursorSelected = play.get('cursorSelected'),
                        cursorX = play.get('cursorX'),
                        cursorY = play.get('cursorY');



                console.log('moveCursor');

                if(cursorSelected){
                    x += cursorX;
                    y += cursorY;

                    this.getBlock(x,y);
                } else {
                    //
                }
            },
4

1 に答える 1

1

コンテキストの問題があります。thisキーワードは、が定義されている場所に関係なく、関数の呼び出し元を表します。keyCode()keyCode()

この試行について詳しく知るために、実行のその瞬間にconsole.log( this )実際に何が起こったかを示します。this

この問題を解決するには、_.bindAll()で遊ぶことができます。

keyCode()が のハンドラーである場合Backbone.View.events、バインディングは既に行われているはずです。

アップデート

これはkeyCode()通常の jQuery イベントのハンドラーです。

$(document).on( 'keydown', this.keyCode );

これでうまくいきます。また、次のようにjQuery.proxy()_.bindAll()を使用することもできます。

$(document).on( 'keydown', $.proxy( this.keyCode, this ) );
于 2012-09-01T09:46:29.243 に答える