简体   繁体   中英

D3 abstract enter() method

Using D3.js, I'm trying to abstract my enter method to a function that determines if this is the first time we need to enter. Could someone please point out why this is not working?

  var firstRender = 0;

  svg.append("g")
    .attr("id", "circles")
    .selectAll("circle")
    .data(data)
    .call(enterStage)  //continue chaining other D3 methods after this is ran
    .append("circle")
    .attr("cx", function(d) {
      return xScale(d[0]);
    })
    .attr("cy", function(d) {
      return yScale(d[1]);
    })
    .attr("r", 2);


  function enterStage() {
    if (firstRender < 1) {
      firstRender++;
      return this.enter();
    } else {
      return this;
    }
  }

You don't need a wrapper, you can simply operate on all the selections:

var sel = svg.selectAll("g.circles").data([1]); // dummy data for top-level element
sel.enter().append("g")
  .attr("id", "circles");

var circleSel = sel.selectAll("circle").data(data);
circleSel.enter().append("circle");
circleSel.attr("cx", function(d) {
    return xScale(d[0]);
  })
  .attr("cy", function(d) {
    return yScale(d[1]);
  })
  .attr("r", 2);

This will work fine even the first time as the enter selection merges into the update selection when you append elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM