绑定类中的d3事件

时间:2017-06-18 20:10:39

标签: javascript d3.js ecmascript-6 this

我想将我的类的实例传递给绑定的d3拖动函数。

我尝试将其分配给变量并传递它。 我最终得到了undefined。

我有点困惑吗?在这种情况下,我如何访问我的班级实例?

谢谢。

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 个答案:

答案 0 :(得分: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);
  }
}   

或者您可以使用bind:

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.
  }

}