Combining data in d3.js

I am a Pythonista and trying to learn d3.js (smile).

I have a server with a socket. My subscription subscribes to it. The server sends updates as JSON '[["id0", 0.38], ["id1", 0.70], ["id8", 0.71]]'. I wrote the following simple page:

<!doctype html>
<html>
  <head>
    <title>WebSockets</title>
  </head>
  <body>
    <script src="http://d3js.org/d3.v2.js"></script>
    <script>
      var ws = new WebSocket("ws://localhost:9999/updates");
      ws.onmessage = function(message)
      {
        var my_data = JSON.parse(message.data);
        var dd = d3.selectAll("#messages")
          .append("div")
          .selectAll("div")
          .data(my_data)
          .enter()
          .append("div")
          .attr("id",function(d){return d[0];})
          .text(function(d){return d[1];})
      }
    </script>
    <div id='messages'></div>
  </body>
</html>

All perfectly! WS receives data. In div#messageshe creates a new one div. And then it puts the data from msg to div#id*. So, after many repetitions, I:

...
<div id="messages">
  <div>
    <div id="id0">0.83</div>
    <div id="id1">0.06</div>
    <div id="id2">0.33</div>
  </div>
  <div> 
    ... 
  </div>
  <div> 
    ... 
  </div>
  ...
</div>
...

How to change the code so that it works as follows:

Having

...
<div id='messages'>
  <div id='id0'>0.25</div>
  <div id='id1'>0.05</div>
  <div id='id2'>0.25</div>
</div>
...

Recieve

'[["id0", 0.38], ["id1", 0.70], ["id8", 0.71]]'

Get result

...
<div id='messages'>
  <div id='id0'>0.38</div>
  <div id='id1'>0.70</div>
  <div id='id2'>0.25</div>
  <div id='id8'>0.71</div>
</div>
...

I mean "if the identifier is given in #messages, then update it and add it to the end . "

I could do it with loops, but the doc says this is done with enter()and exit()..

, (circle, join) , . , . , .


PS: Python, . , d3 - . , , d3 - , .


PPS: - - .



UPDATE

,

d3.select("#messages")
  .select("div")
  .selectAll("div")
  .data([["id0",0]], function(d){return d[0];})
  .enter()

[null]

d3.select("#messages")
  .select("div")
  .selectAll("div")
  .data([["id0",0]], function(d){return d[0];})

[HTMLDivElement] HTMLDivElement.__data__ == ["id0",0]

d3.select("#messages")
  .select("div")
  .selectAll("div")
  .data([["id0",0]], function(d){return d[0];})
  .exit()

[null, HTMLDivElement, HTMLDivElement] "id1" "id2" HTMLDivElement.__data__[0] .

?

+3
1

, . ?

var my_data = JSON.parse(message.data);
var my_selection = d3.selectAll("#messages")
  .selectAll("div")
  .data(my_data, function(d){return d[0];})
my_selection
  .enter()
  .append("div")
  .attr("id",function(d){return d[0];})
my_selection
  .text(function(d){return d[1];})

, , - ?

+1

All Articles