D3js v3到v4 migraiton合并

时间:2018-02-12 19:59:19

标签: javascript d3.js

当我尝试将我的d3js图从版本3迁移到版本4时,我遇到了一些问题。我已经解决了很多问题,但我不理解“合并”如何工作。在此代码中,数据标题属性未在V4中设置,并且contextmenu不起作用。 有什么问题?我不明白合并是如何工作的。有人可以解释我如何修复此代码以及为什么我必须以这种方式修复它,因为我有更多的图表需要修复。

    var slice = self.svg.select(".slices").selectAll("path.slice")
        .data(pie(new_node_data), key);

    slice.enter()
        .insert("path")
        .attr("class", "slice").attr("fill", function(d2) { return color(d2.data.name);} )
        .merge(slice) //<-- merge back in update selection
        .transition().duration(1000).attrTween("d", tweenIn);

    slice.attr('data-title',function(d){
        return d.data.period + ' ' + d.data.name;
    })

    slice.on("contextmenu", function(d,i){
        console.log(d.data);
        self.context_menu(d.data, i, false);
    });
    self.attach_graph_items_click_event_handler(slice, false, true);

1 个答案:

答案 0 :(得分:1)

您遗漏了一些简单的内容,合并后您不会将合并的update + enter保存回变量(您错过了slice =):

slice = slice.enter() //<-- SAVE IT TO A VARIABLE
  .insert("path")
  .attr("class", "slice").attr("fill", function(d2) { return color(d2.data.name);} )
  .merge(slice)
  ....

这里有评论细分:

// this is your update selection
// slice is a selection of all the things being updated
// in your collection path.slice
var slice = self.svg.select(".slices").selectAll("path.slice")
  .data(pie(new_node_data), key);

// .enter returns the enter selection
// all the things that are being added
slice = slice.enter()
  .insert("path")
  .attr("class", "slice").attr("fill", function(d2) { return color(d2.data.name);} )
  // this merges the update slice with the enter slice
  .merge(slice)
  // this is now operating on enter + update
  .transition().duration(1000).attrTween("d", tweenIn);
相关问题