Y.Wang
Y.Wang

Reputation: 149

Changing interactions from D3 v3 to v4

I have spent more 5 hours for changing this pie chart into D3 v4, but it still doesn't work well (that is, the interactions are not running ).

Here is where they are set:

paths.enter()
    .append('svg:path')
    .attr('d', arc)
    .style('fill', function(d, i) {
        return color(i);
    })
    .style('stroke', '#FFFFFF')
    .on(eventObj)

Upvotes: 2

Views: 92

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

As you can see, in that D3 v3 example the selection.on...

paths.on(eventObj)

...receives an object with all the type listeners:

var eventObj = {
    'mouseover': function(d, i, j) {
        //etc...
    },
    'mouseout': function(d, i, j) {
        //etc...
    },
    'click': function(d, i, j) {
        //etc...
    }
};

And here lies the problem: that works in D3 v3, but not in v4.

Look at this demo, using D3 v3 (hover over the circle):

const events = {
  "mouseover": function() {
    console.log("mouseover")
  },
  "mouseout": function() {
    console.log("mouseout")
  }
};

d3.select("circle").on(events)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<svg>
  <circle cx="100" cy="50" r="25"></circle>
</svg>

Now the exact same code, but using D3 v4:

const events = {
  "mouseover": function() {
    console.log("mouseover")
  },
  "mouseout": function() {
    console.log("mouseout")
  }
};

d3.select("circle").on(events)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<svg>
  <circle cx="100" cy="50" r="25"></circle>
</svg>

It doesn't work. It doesn't throw any error, it simply fails silently.

Solution: set each event listener separately:

paths.on("mouseover", etc...)
    .on("mouseout", etc...)
    .on("click", etc...);

Upvotes: 2

Related Questions