我有一个反应折线图,每隔1秒,它的数据就会被改变,这些变化必须通过反应方法来表达。这是我在客户端的代码:
var waitList=[Meteor.subscribe("line_chart_data")];
Deps.autorun(function(){
// http://underscorejs.org/#every
var waitListReady=_.every(waitList,function(handle){
return handle.ready();
});
if(waitListReady){
console.log("Every documents sent in publications is now available.");
var data = Data.find();
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
if (d3.select("#line_chart").length > 0)
{
document.getElementById("line_chart").innerHTML = "";
}
var svg = d3.select("#line_chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
console.log("onReady And the Itemns actually Arrive", arguments);
var num = data.count();
var dataPoints = []; // create an empty array
data.forEach(function(d) {
dataPoints.push({
id: d._id,
date: new Date(d.Year, d.Month, d.Day),
close: +d.Close
});
});
data = dataPoints;
x.domain(d3.extent(data, function(d) {
return d.date;
}));
y.domain(d3.extent(data, function(d) { return d.close; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
}
});
显示的所有数据都在名为Data的集合上,该集合在服务器端发布。最终结果嵌入在html div bar_chart
中,但问题是在保持程序运行一段时间之后,可视化和数据之间的延迟变化显着增加,因此数据的更改不会与监视器上显示的内容同步。我认为这源于每次自动运行中的所有块都将重新运行的事实。我使用了一个observe方法来处理这个问题:
Observe = Data.find({}, {fields: {Close: 1, Year: 1, Month:1, Day:1}}).observe({
added: function (document) {
var dataPoint = [];
dataPoint.push({
id: document._id,
date: new Date(document.Year, document.Month, document.Day),
close: +document.Close
}
);
svg.append("path")
.datum(dataPoint)
.attr("class", "line")
.attr("d", function(d) {return line(d)})
.attr("id", "path-" + document._id);
},
changed: function(newDocument, oldDocument){
svg.select("#path-"+ newDocument._id)
.datum(newDocument);
}
})
以上代码永远不会有效。我想,不可能在svg的末尾添加一个路径并只传递当前文档 我的问题是如何重构第一个代码来使用observe方法而不是Deps.autorun?
数据格式如下:
Year Month Day Close
12 May 1 582.13
... ... ... ......
并且有大约1000条记录直接插入mongodb。