caffeine_inquisitor
caffeine_inquisitor

Reputation: 727

d3 - updating data doesnt cause a refresh

I'm trying to write a simple d3js app which will display a graph from an array of object literals. This literal will be updated on regular basis (from the backend). But for simplicity sake, I have rewritten it using setInterval() which should update the content.

<!doctype html>
<html>
<head>
    <script src="d3.js" type="text/javascript"></script>
    <script src="underscore.js" type="text/javascript"></script>
</head>
<body>
<div id="graph">

</div>

<script type="text/javascript">
    var data=[
        { name: 'NONE', distribution: 5}
    ];
    var graphElement = d3.select("#graph");
    // set initial data
    graphElement.selectAll("p")
            .data(data, function(d){return d.name} )
            .enter()
            .append("p")
            .text(function(d){return d.name + d.distribution;});

    var redraw= function() {
        console.dir(data);
        graphElement.selectAll("p")
                .data(data, function(d){return d.name})
                .enter()
                .append("p")
                .text(function(d){return d.name + d.distribution;});
    };


    setInterval(function() {
        var advice = _.find(data, function(i){return i.name == 'ADVICE'});
        if (!advice){
            advice = {name: 'ADVICE', distribution: 0};
            data.push(advice);
        }
        advice.distribution = advice.distribution + 1;
        redraw();
    }, 3000);
</script>

</body>
</html>

The page will initially displays one paragraph (as expected). Then the setInterval() kicks off, and insert an 'ADVICE' method with value of 1. Again, as expected. But when the subsequent setInterval() kicks off, the 'ADVICE' node is not updated - i.e. it stays off as 'ADVICE1'.

Have I missed something obvious here?

Thanks for the help!

Regards,

Alex

Upvotes: 1

Views: 626

Answers (1)

FernOfTheAndes
FernOfTheAndes

Reputation: 5015

There are a few things to note here:

1) the enter/update selections were not being properly handled;

2) your advice.distribution was not changing from 1.

UPDATE FIDDLE with refresh of ADVICE string.

var ge = graphElement.selectAll("p")
    .data(data, function(d){return d.name});

ge.exit().remove();

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

ge.text(function(d){return d.name + d.distribution;});

Upvotes: 1

Related Questions