Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.event not working when combining modules

I have a code where I'm importing (es6 import statement) d3-selection and d3-transition. However I also need to capture event. When I don't import d3-transition the d3.events works perfectly. As soon as I import d3-transition I get an error stating that d3.event is null and cannot reference event properties.

There is a note in the D3 API Reference.

https://github.com/d3/d3-selection/blob/master/README.md#event: If you use Babel, Webpack, or another ES6-to-ES5 bundler, be aware that the value of d3.event changes during an event! An import of d3.event must be a live binding, so you may need to configure the bundler to import from D3’s ES6 modules rather than from the generated UMD bundle; not all bundlers observe jsnext:main. Also beware of conflicts with the window.event global.

I'm using babel (for ie11 support) and webpack for bundling. What does this note mean? Why doesn't something like import {event as d3event} from'd3-selection'; followed by let d3 = Object.assign({}, d3selection, d3transition, d3event}; work?

like image 301
Wanderer Avatar asked Nov 08 '22 06:11

Wanderer


1 Answers

import {event as d3event} from'd3-selection'
d3event === null // true; `event`'s value changes later with user input.
let d3 = Object.assign({}, d3selection, d3transition, d3event)
// won't have an `event` property since Object.assign({}, null) -> {}

Adding d3.event = event // or d3 = {event} will still return the null event observed at assignment time; see Mike Bostock's method of getting the current event for a solution.

The d3.event note now contains a link to an explanation of what a live binding is: a reference to a variable within d3-selection.

An additional caveat which cost me some time: if d3-drag is pointing to a different version of d3-select than your other tools, d3.select(/**/).call(d3.drag(/**/)) won't work, since events never reach the event variable that d3.drag is using. Somewhere around d3@^5, the main package no longer pins the d3-selection version, allowing this sort of mismatch.

like image 170
Steven Kalt Avatar answered Nov 14 '22 21:11

Steven Kalt