2012-02-14 17 views
0

私はこの場合実際に何をしているのか疑問に思っていますが、私はslickgridのカスタムエディタを作っています。それでは、私はこの漠然とセットアップのようなものを持っているとしましょう:イベントにバインドされた別の関数からイベントにバインドされた関数を呼び出すことができません

function TestEditor(args) { 
var $test0, $test1; 
//other variables 

this.init = function() { 
    //various init stuff, it all works fine 
    //init $test0 and $test1, also works fine 

    $test0.bind("change", this.test0Changed); 
    $test1.bind("change", this.test1Changed); 

    this.test0Changed(); //this works fine too, makes the nested call to test1Changed 
} 

this.test0Changed = function() { 
    //does various operations 
    this.test1Changed(); //calls test1Changed, this works _unless_ test0Changed is called through an event, then the code breaks here! 
    //stuff that won't happen when the code breaks at the previous call 
} 

this.test1Changed = function() { 
    //stuff, works fine unless called by test0Changed triggered by an event, then nothing 
} 

//whatever, lots of other stuff, it all works 

this.init(); 
} 

私はtest0Changedがtest1Changedに電話をしたい、と私は明示的にthis.test0Changed(に自分自身を呼び出す作る場合、それは正常に動作します)コードで。しかし、test0Changedが 'change'イベントによってトリガされると、コードはthis.test1Changed()を呼び出そうとするとブレークします。私がthis.test1Changed()への呼び出しをコメントアウトすると、すべて問題ないので、問題の原因となっているのはその正確な行です。これを引き起こしているのは何ですか?

+0

は '何ですテスト変数は破線で示されていますか? – paislee

+0

おっと、それはダムだった、私はこれを意味した – user173342

答えて

3

機能が.bind()になると、それは「this」の値を「記憶していない」ためです。

ハンドラとして、thisがイベントを受信した要素になります。ここで

this.init = function() { 

    var self = this; 

    $test0.bind("change", function() {self.test0Changed.apply(self, arguments);}); 
    $test1.bind("change", function() {self.test1Changed.apply(self, arguments);}); 

} 

私はあなたが変数で使用するthisを参照して、私は関数を呼び出すthis値を参照し、使用無名関数を可決しました。


私はまた、すべての元の引数が渡されることを保証するために.applyを使用。それが必要でない場合は、

this.init = function() { 

    var self = this; 

    $test0.bind("change", function() {self.test0Changed();}); 
    $test1.bind("change", function() {self.test1Changed();}); 

} 

それともthis値を保持するために、jQueryの$.proxyを使用することができます...これにそれを変更することができます...

this.init = function() { 

    $test0.bind("change", $.proxy(this, 'test0Changed')); 
    $test1.bind("change", $.proxy(this, 'test1Changed')); 

} 
+0

ああ、そのコンテキストでこれを得るための方法はありますか?それと、両方の種類の通話に対応するには? – user173342

+0

構文?閉じる '}' – paislee

+0

ありがとう@paislee:私は更新します。 –

関連する問題