Skip to content

selection.join() enter and update duplication #260

@xy2i

Description

@xy2i

In What Makes Software Good, it's mentionned that doing things both on enter and update introduces duplication, like in this code:

var text = g
  .selectAll("text")
  .data(data, key); // JOIN

text.exit() // EXIT
  .remove();

text // UPDATE
  .attr("x", function(d, i) { return i * 32; });
  
text.enter() // ENTER
  .append("text")
    .attr("x", function(d, i) { return i * 32; }) // 🌶
    .text(function(d) { return d; });

In D3 v4, there's the selection.merge() API which works around this problem by merging both enter and update:

var text = g
  .selectAll("text")
  .data(data, key); // JOIN

text.exit() // EXIT
  .remove();

text.enter() // ENTER
  .append("text")
    .text(function(d) { return d; })
  .merge(text) // ENTER + UPDATE
    .attr("x", function(d, i) { return i * 32; });

But, with the selection.join() API, it seems the same problem is present again:

var text = g
  .selectAll("text")
  .data(data, key)
  .join(
    enter => enter.append("text")
      .attr("x", (d, i) => i * 32)
      .text(d => d),
    update => update
      .attr("x", (d, i) => i * 32), // 🌶
    exit => exit.remove()
  )

Is there a way to do this with join() without the duplication?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions