2017-06-18 29 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

非常感謝你但這給了一個語法錯誤。(Unexpected token =)另外我需要在同一個方法中訪問我的類的引用和this(因爲它指向事件目標)。 –

+0

編輯我的答案,我在想你使用es 6瀏覽器。好的,我已經使method2成爲一個函數。由於它的功能,你現在可以訪問它了。 – Cyril

+0

是的,我也嘗試過這種方法,es6功能工作,我使用最新的Chrome。我也試過'嚴格使用'。不知何故,我認爲=在一個類的方法定義是無效的,我想。你試過了嗎? –