我使用d3创建了一个力布局,效果很好.我的初始数据是从json文件加载的,并且使用与此d3.js示例类似的技术绘制图表:

现在图表在屏幕上,我需要通过Web套接字从我收到的数据中动态添加,更新和删除节点.我添加和删除方法工作,但我找不到更新现有节点属性的正确方法.
从我所进行的阅读中我收集正确的技术是更改数据源,然后使用enter()方法更新图表.
要更新节点,我正在执行以下操作:
function updateNode(id, word, size, trend, parent_id){
var updateNode = nodes.filter(function(d, i) { return d.id == id ? this : null; });
if(updateNode[0]){
updateNode.size = Number(size);
updateNode.trend = trend;
nodes[updateNode.index] = updateNode;
update();
}
}
Run Code Online (Sandbox Code Playgroud)
然后,更新功能使用以下命令更新节点:
function update(){
node = vis.selectAll('.node')
.data(nodes, function(d) {
return d.id;
})
createNewNodes(node.enter());
node.exit().remove();
force.start();
}
function createNewNodes(selection){
var slct = selection.append('g')
.attr('class', 'node')
.call(force.drag);
slct.append('circle')
.transition()
.duration(500)
.attr('r', function(d) {
if(d.size){
return Math.sqrt(sizeScale(d.size)*40);
}
})
}
Run Code Online (Sandbox Code Playgroud)
我采取了正确的方法吗?当我尝试这个代码时,我尝试在圆上设置radius属性时获得的节点是节点数组中的最后一个节点.即包含分层节点数据而不是单个节点对象的那个.
任何指针都会非常感激,我花了太多时间在这:)