我有一个d3.js树形图,每次服务器发出更新时都会对其执行ping操作。更新来自Twitter流。有很多更新。因此,树形图的动画非常生涩,因为在1500毫秒过渡完成之前,树形图已多次更新。
是否可以将更新节点值的代码与更新视图的代码分开?我希望找到一个解决方案,该解决方案将不断更新树形图的值,但仅每1500-2000ms更新一次视图。
请查看我的完整d3 script:
var socket = io.connect();
var margin = {top: 40, right: 10, bottom: 10, left: 10},
width = 1000 - margin.left - margin.right,
height = 650 - margin.top - margin.bottom;
var color = d3.scale.category20c();
var treemap = d3.layout.treemap()
.size([width, height])
.sticky(false)
.value(function(d) { return d.size; });
var div = d3.select("body").append("div")
.style("position", "relative")
.style("width", (width + margin.left + margin.right) + "px")
.style("height", (height + margin.top + margin.bottom) + "px")
.style("left", margin.left + "px")
.style("top", margin.top + "px");
var root;
socket.on('update', function(stream) {
console.log('tweets')
div.datum(root).selectAll(".node").remove();
root = stream.masterlist;
var node = div.datum(root).selectAll(".node")
.data(treemap.nodes)
.enter().append("div")
.attr("class", "node")
.call(position)
.style("background", function(d) { return d.children ? color(d.name) : null; })
.text(function(d) { return d.children ? null : d.name; });
d3.selectAll("input").on("change", function change() {
var value = this.value === "count"
? function() { return 1; }
: function(d) { return d.size; };
node
.data(treemap.value(value).nodes)
.transition()
.duration(1500)
.call(position);
});
});
function position() {
this.style("left", function(d) { return d.x + "px"; })
.style("top", function(d) { return d.y + "px"; })
.style("width", function(d) { return Math.max(0, d.dx - 1) + "px"; })
.style("height", function(d) { return Math.max(0, d.dy - 1) + "px"; });
}
这段代码是从bl.ocks.org网站上的treemap example取而来的,仅作了细微的更改(我的数据来自回调而不是json)。我试图用
setInterval()
以外的socket.on()
从视图逻辑中拆分值逻辑,但是我的尝试要么未能减慢转换速度,要么完全破坏了树形图。 d3.selectAll("input").on("change", function change() {
var value = this.value === "count"
? function() { return 1; }
: function(d) { return d.size; };
});
}); // end socket.on();
setInterval(function() {
node
.data(treemap.value(value).nodes)
.transition()
.duration(1500)
.call(position);
}, 2000);
非常感谢您的见解!
最佳答案
您要执行的操作称为反跳。有几个javascript库可供您使用(我使用下划线)。您也可以自己写一个。我在a blog post中找到了这个:
function debounce(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
一旦您实现或偷取了一个防抖动功能,其余的操作就很容易了:您只需使用debounce包裹处理更新的函数即可:
socket.on('update', debounce(function(stream) {
console.log('tweets')
...
}));