D3.js is a super cool and very powerful library for creating some really interesting visualizations.
One of the problems that I ran into recently was regarding the “this” keyword in D3 functions. For example, in regular old javascript you would do:
Which is fine. “this” is scoped to the function, so it would point back to the “svg” object.
In TypeScript, “this” works differently.
When the code is transpiled to javascript, “this” gets turned into something that points back to the class object… so what the heck do you do?
Method 1:
If you have a reference to the object that the mouse event is using, you can pass in its .node() method and that will do the trick.
Method 2:
D3 has a handly event.currentTarget property that will be scoped to the target that raised the event. For our case, that works like a charm.