How to access previous data value before binding the new value in d3.js?

942 views Asked by At

I'm new to d3 and trying to implement a force simulation updating itself with real-time data. To make it easy, with each d3.interval I assign a random value to "bitrate" key of each node. My aim is to access the previous data value before binding the new data, thus set the rules of transition based on relation between them. I tried the brilliant method that AmeliaBr has explained in this post: Compare/Diff new data with previous data on d3.js update. It makes so much sence but when I try it and print the d.bitrate and this.__oldData__.bitrate values, they are always equal to each other. Weird thing, when I check them from the dev-tools they have different values. I also tried guerilla moves such as accessing __oldData__ by (d3.select(this)._group)[0][0], but it returns undefined :/ I think I'm soo confused and stuck that I can't see where I skip. Here is the screenshot from devtool and below is my code. Thanks!

function updateData(){

link = link.data(links, function(d) {return d.id})
         .enter()
         .append("line")
         .merge(link);

     link.transition(3000)
         .attr("stroke",function(d) {
            if ( d.target.bitrate > d.source.bitrate){
            return "green"}
          })

label = label.data(nodes)
           .enter()
           .append("text")
           .merge(label);

       label.transition(1000)
           .text(function(d){ return d.name; })


 node = node.data(nodes,function(d){return d.id})
            .enter()
            .append("circle")
            .merge(node);

        node.on("mouseover",mouseover)
            .on("mouseout",mouseout)
            .call(d3.drag().on("start",dragstarted)
                           .on("drag",dragged)
                           .on("end",dragended)
             )
            .transition(1000)
                           .attr("r",40)
                           .attr("stroke-width",function(d,i){
                              if (this.__oldData__){
                                console.log(this.__data__.bitrate);
                                console.log(this.__oldData__.bitrate);
                           }
                         })



   simulation.nodes(nodes);
   simulation.force("link").links(links);
   simulation.alpha(1).restart();
 }

d3.interval(function(){

nodes.map(function(n){n.bitrate = Math.round( Math.random() * 10000 )})

node = node.property("__oldData__", function(d){return d; });
updateData();

},2000)
0

There are 0 answers