catlovespurple
catlovespurple

Reputation: 692

D3 what is the difference between these two way of data binding?

I wonder why these two code snippets will render different results when there are existing DOM elements in the body? When I have only one "dog" element in the body old the results is - dog. 20 30 2 32 4 1.

However, if I have 10 dog p elements(which is larger than the dataset length), then the html will just give me 10 dogs p element, with nothing updated.

The 2nd code snippet render the right results as I expect. Updating the exiting p elements with dataset value.

From my understanding, enter will compare the existing DOM elements with dataset values and update the DOM elements according to new data. Why the first one does not work as expected?

<body>
    <p>dog.</p>
    <p>dog.</p>
    <p>dog.</p>
    <p>dog.</p>
    <p>dog.</p>
</body>

First one:

var dataset = [10,20,30,2,32,4,1];

d3.select("body")
            .selectAll("p")
            .data(dataset)
            .enter()
            .append("p")
            .text(function(d){return(d);});

Second one:

var dataset = [10,20,30,2,32,4,1];

    elements = d3.select("body").selectAll("p")
                .data(dataset)

    elements
           .enter()
           .append("p");

    elements.text(function(d){return(d);});

Upvotes: 0

Views: 121

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

The first snippet operates only on the enter selection, the second snippet also on the update selection. So if there are existing elements that are matched by the data, the first snippet won't change them while the second will.

The .data() call returns the update selection and you get the enter and exit selections by calling .enter() and .exit() on it. As you are not doing that in the second snippet when setting .text(), the operation is performed on the update selection (i.e. the elements that are already there and have been matched by data plus the elements from the enter selection for which you have appended new elements just before).

Upvotes: 1

Related Questions