簡體   English   中英

在類中綁定d3事件

[英]binding d3 event in a class

我想將我的類的實例傳遞給綁定的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.
  }

} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM