kjo
kjo

Reputation: 35301

Still confused by d3's enter method

The trigger for this question is the following snippet of code by d3.js's author (context):

      // Select the svg element, if it exists.
      var svg = d3.select(this).selectAll("svg").data([data]);

      // Otherwise, create the skeletal chart.
      var gEnter = svg.enter().append("svg").append("g");
      gEnter.append("path").attr("class", "area");
      gEnter.append("path").attr("class", "line");
      gEnter.append("g").attr("class", "x axis");

What throws me off are the comments, especially the "Otherwise" in the second one.

More specifically, the wording of these comments suggests to me that the snippet above would be equivalent to the following:

    var svg = d3.select(this).selectAll("svg").data([data]);

    if (svg.length == 0 || svg[0] === undefined) {
        // svg element does not yet exist
        var gEnter = svg.enter().append("svg").append("g");
        gEnter.append("path").attr("class", "area");
        gEnter.append("path").attr("class", "line");
        gEnter.append("g").attr("class", "x axis");
    }

...or maybe even to the following:

    var svg = d3.select(this).selectAll("svg");

    if (svg.length == 0 || svg[0] === undefined) {
        // svg element does not yet exist
        var gEnter = svg.enter().append("svg").append("g");
        gEnter.append("path").attr("class", "area");
        gEnter.append("path").attr("class", "line");
        gEnter.append("g").attr("class", "x axis");
    }
    else {
        // svg element already exists
        svg.data([data]);
    }

Is any one or the other of these two apparent equivalences actually correct?

If not, what do the four lines of code after the second comment (// Otherwise...) do when the svg element does already exist?

Upvotes: 1

Views: 147

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

The comments are misleading on their own and you have to consider them in their context. Specifically, .data() is passed a single-element array, i.e. will only ever match a single element. The whole construct is just a shortcut for doing what's mentioned in the comments -- check if an element exists and if not, create it.

What happens is the following. The code selects all SVGs and matches a single datum to them (data). So if there is an SVG already, it will be in the update selection and the enter selection will be empty. If not, the enter selection will have a single element. This is what the "otherwise" refers to -- the "else" is implicit because only the enter selection is handled.

The code, in this specific context, is equivalent to both of the snippets you've posted. It's just shorter.

Upvotes: 2

Related Questions