javascript - 在类中绑定(bind) d3 事件

标签 javascript d3.js ecmascript-6 this

我想将我的类的实例传递给绑定(bind)的 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.


  }

}    

最佳答案

您可以将其设为一个函数,并将其传递到您将有权访问 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.
  }

} 

关于javascript - 在类中绑定(bind) d3 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44619102/

相关文章:

javascript - 将节点移动到某个位置而不拖动

svg - 如何根据 d3.js 中的索引分配颜色?

javascript - 如何将 CSS 样式应用于 AJAX 调用后呈现的内容

angular - 添加StoreModule.forFeature(...)后无法访问存储的数据

javascript - Bootstrap 3.0 : How to make vertical navbar dropdown not append to only last list item?

javascript - 在单个页面上添加多个 bootstrap 4 轮播

JavaScript 确保所有数字都是唯一的,如果不是加一(或更多)

javascript - 使用 Node.js 和 Express 创建 HTTPs 服务器

javascript - 一组矩形的 D3.js 过渡

javascript - 过滤对象键不为空的数组