How to translate ‘this’ in D3 JavaScript to TypeScript?

As already stated in this comment and this answer, this does not have a different meaning between JavaScript and TypeScript.

That being said, your problem here is way more prosaic: you’re trying to use this in an arrow function to get the current DOM element, and that will simply not work.

So, in a nutshell, the problem here is the difference of this between an arrow function and a regular function, not between TypeScript and JavaScript.

Solution

There is an alternative to this, described everywhere in the API: when you use an anonymous function in most of D3 methods, the arguments being passed are…

… the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]).

Thus, this is simply the current index (the second argument) of the nodes groups (the third argument).

So, in the snippet below:

selection.on("foo", function (d, i, n){
    console.log(this)
    console.log(n[i])
})

The two console.log will return the same thing.

As you are using an arrow function, the solution is (in JavaScript):

this.nodes.on("click", (d, i, n) => {
    d3.select(n[i])//rest of your code here
})

If you want to read more about the use of the second and the third arguments to get the DOM element, have a look at this example: d3 v4 retrieve drag DOM target from drag callback when `this` is not available

Leave a Comment