2017-06-18 26 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。我也试过'严格使用'。不知何故,我认为=在一个类的方法定义是无效的,我想。你试过了吗? –