2017-06-18 5 views
0

私のクラスのインスタンスをバインドされたd3ドラッグ関数に渡したいとします。クラス内のd3イベントのバインド

これを変数に代入して渡します。 私は未定義で終わります。

私は少し混乱していますか?この場合、私はどのようにクラスのインスタンスにアクセスしますか?

ありがとうございます。

class foo { 

    constructor(a){ 
    this.a = a; 

    } 
    method1(){ 

    var referenceToMyClass = this; 

    this.dragEvent = d3.drag(referenceToMyClass) 
    .on("drag", this.method2); 

    d3.select('target id').call(this.dragEvent); 
    } 
    method2(){ 

    //Here i want to access referenceToMyClass; 
    //referenceToMyClass is undefined. 
    //this refers to the event target. 


    } 

}  

答えて

1

あなたはそれを機能させることができますし、thisにアクセスする必要があります機能でそれを伝承:

class foo { 

    constructor(a){ 
    this.a = a; 

    } 
    method1(){ 

    var referenceToMyClass = this; 
    var method2 = function(){ 
     //do something with referenceToMyClass 
    }  
    this.dragEvent = d3.drag(referenceToMyClass) 
    .on("drag", method2); 

    d3.select('target id').call(this.dragEvent); 
    } 
} 

またはバインドを使用することができます。

class foo { 

    constructor(a){ 
    this.a = a; 
    this.method2.bind(this); 
    } 
    method1(){ 

    var referenceToMyClass = this; 

    this.dragEvent = d3.drag(referenceToMyClass) 
    .on("drag", this.method2); 

    d3.select('target id').call(this.dragEvent); 
    } 
    method2(){ 
    //this refers to the object now. 
    } 

} 
+0

はありがとうございましたしかし、これは構文エラーを与えます。(予期せぬトークン=)また、私は同じメソッドでクラスとこれ(イベントターゲットを参照)への参照にアクセスする必要があります。 –

+0

私の答えを編集しました。私はes 6ブラウザを使用していると思っていました。私はmethod2を関数にしました。その関数からアクセスできるようになりましたので、今すぐチェックしてください。 – Cyril

+0

うん、私もこのメソッドを試しました、es6関数が動作する、私は最新のChromeを使用します。私はまた、 '厳密な使用'を試みました。どういうわけか、私は=クラスのメソッド定義で=私はおそらく有効ではないと思う。それを試しましたか? –

関連する問題