A possible cause for the issue is that the d3
version used in the first example is not v6.0. There was a significant change from v5.x to v6.0 where the event is no longer a global variable but passed as a parameter in callbacks.
Your code is in v6.0 style, so it works in the second example, where it is explicitly importing v6.0 from https://d3js.org/
You can confirm if your original code is running d3 v6.0 with a console.log(d3.event)
inside one of the callbacks:
.on("drag", () => {
console.log(d3.event);
})
If the code above logs the event, it means your d3 is in version v5.x.
If it works, but typescript also gives a type error anyway, it means that your typings (@types/d3
) are for v6.0, so they are not aligned with the installed version of d3.
In any case, if d3.event
works, then the easiest solution is to update your d3 to v6.0 since you already have the code compatible with the latest version.
The second parameter of the callback is the datum bound to the element. In your example, it is expected to be undefined
because there is no datum associated with the circle (i.e., there is no .selectAll(...).data(...)
before the .append()
). If interested, you could check a d3-drag example in v.6.0 that uses data binding to understand it better.
So, a minimal drag behavior example in v5.0, without data binding, would be:
.on("drag", function() {
d3.select(this).attr("cx", d3.event.x).attr("cy", d3.event.y);
})
And in v6.0:
.on("drag", function(event) {
d3.select(this).attr("cx", event.x).attr("cy", event.y);
})
Node: Remember to use the function
keyword instead of an arrow function (() => ...
) if you want acess to the correct this
object inside it