twilliams
twilliams

Reputation: 475

How to recover the typescript 'this' scope from a d3 function?

D3 overwrites the 'this' variable, allowing you to see the current selection while in different methods.

I also need 'this' to access class member properties in typescript. I'm currently unsure of how I can retain both whenever I need them.

tweenArc(datum: any, index: number, attr: string) {
    console.log(this);
    console.log(this.classVariable);
...
}

The first console.log will write out the d3 selection, which in this case is an svg element.

If I'm trying to access member properties from the class the function is defined in however, I cannot. That console.log returns undefined.

Upvotes: 3

Views: 862

Answers (1)

twilliams
twilliams

Reputation: 475

One solution I have come up with is to change the way I am defining my callback. Instead of putting the callback as a function in the typescript class, I am creating it inline with a lambda, so I have access to my selection which is defined in the wrapping class, plus access to the this variable of the typescript class.

If there's a better way I would like to know, since this forces a specific architecture.

selection.transition()
            .duration(this.duration)
            .attrTween("d", (datum: any, index: number, attr: string) => {
                let previousEndAngle = parseFloat(selection.attr("endAngle"));
                let endAngle = this.d3Utility.arcPercentage(value, maxValue, startAngle, isClockwise, this.arcLength);
                let interpolator = d3.interpolate(previousEndAngle, endAngle);

                return (t: number): any => {
                    selection.attr("endAngle", interpolator(t));

                    return this.drawArc(startAngle, interpolator(t), radii[0], radii[1])(null);
                }
            });

Upvotes: 1

Related Questions