0

i have a following code inside angular directive, i wanted to access class level variable inside the call back function so i used the arrow function but the 'this' is still not pointing to directive.

this.itemRects.selectAll('rect')
            .data(this.visItems, (d) => {
                return d.id + this.x;
            })

i added debugger at the return statemententer image description here on the debugger it shows this pointing towards data array.

how can i access directive level 'this' inside callback function?

arshid dar
  • 1,355
  • 2
  • 15
  • 23

1 Answers1

3

In the call back function , this refers to callback function object. you can declare a variable outside of callback function like this:

var self = this;

and access class variables in call back function using self, instead of this.

Please check below link to bind class variables in call back function using arrow symbol: How to use arrow functions (public class fields) as class methods?

Try:

this.itemRects.selectAll('rect')
            .data(this.visItems, (d,x) => {
                return d.id + x;
            })
Vipul
  • 545
  • 1
  • 8
  • 30