Reputation: 831
Say we have a force diagram of 4 interlinked nodes (how they linked dont matter for this situation):
{name: A, age: 15}
{name: B, age: 5}
{name: C, age: 4}
{name: D, age: 66}
Now I receive two nodes:
{name: E, age: 12}
{name: A, age: 7}
I am going to update the graph which is now going to have 5 nodes in total, but I also would like to update the age of matching nodes. So the end result (age) of node A would be 22.
The procedure I'm following is:
node = svg
.selectAll(".node")
.data(nodes, function (d) { return d.name; });
var nodeEnter = node
.enter()
.append("g")
.attr("class", "node");
nodeEnter
.append("circle")
.attr("r", 5);
So somewhere in here Id like to sum the age property. Any ideas anyone ?
Upvotes: 0
Views: 348
Reputation: 108
Previously with D3, (before v4) you were not able to compare a node's old and new data values during the update step without storing the data as a javascript property of the DOM object for the element, similar to how data is stored in D3's data property.
This process of storing local variables has been made part of the library in v4 with the d3.local() method.
The way it works is you declare a local data variable a la
var persistedData = d3.local();
and then, call persistedData.set(this, d.age);
for each node and call persistedData.get(this)
to retrieve that previous age data where you are appending the age data to the dom for presentation.
nodeEnter
.append("text")
.attr("dx", 12)
.attr("dy", "2em")
.text(function(d) {
var oldAge = persistedData.get(this);
return oldAge ? oldAge + d.age : d.age;
});
Upvotes: 2
Reputation: 157
I believe what you need to implement is the General Update Pattern read more here. And you'll need to use key functions on your .data() method. Mike has an example here. It shouldn't be too hard, let me know if you have some problems.
Upvotes: 0