0

This question will sound a bit odd, but I will explain the reason. I am using d3.js combined with Angular. everything is fine, but sometimes there are events within the logic of d3.js in which "this" is a different value from the context of angular. For this reason I would like to know if there is a way to directly access the variables that I have defined in my component in the style of:

HomeComponent.myVar   //HomeComponent name of my current component

Instead of

this.myvar

this is a example of my problem using d3.js

Node.on("mouseout", unfocus);

function unfocus(){
 console.log(this); //problem context angular
}

Node.mouseover(function(d){
 console.log(this); //this is not context angular, is a value of this event
 console.log(HomeComponent.myvar); //not works, but is my idea
 })

thank you.

yavg
  • 2,761
  • 7
  • 45
  • 115
  • Try `Node.mouseover((d) => { ... })`. – ConnorsFan Aug 13 '19 at 14:01
  • @ConnorsFan Thanks, I put an example, but I just updated my real problem. – yavg Aug 13 '19 at 14:04
  • Try `unfocus = () => { console.log(this; }`. – ConnorsFan Aug 13 '19 at 14:05
  • @ConnorsFan I appreciate your help, but I am somewhat confused. I need to have the context of d3.js and the context of angular. in this way he would lose the context of d3.js – yavg Aug 13 '19 at 14:08
  • @ConnorsFan I would think that the best way to solve this problem is to be able to access the angular variables in some way without using the "this" – yavg Aug 13 '19 at 14:16

2 Answers2

0

The comments explain that you can use another syntax to still be able to access this:

Node.mouseover(d => {
    console.log(this);
})

If you really want to keep the other syntax, which I don't recommend, you can store this in another variable:

let self = this;

Node.mouseover(function(d){
    console.log(self);
})

I don't recommend it because it's harder to understand, it's error prone, and it's not always clear what the scope of the variable is.

AntoineB
  • 4,535
  • 5
  • 28
  • 61
0

try placing your variables outside of the class' scope with a var/let/const keyword. you could than try and access the variable without "this"

Julian Dave
  • 105
  • 1
  • 12