[英]Meteor update flot chart
使用Meteor 0.8.0時 ,如何在新數據到貨時更新flot圖表? 我查看了Meteor-flot上的示例,但它正在通過頁面上的計時器更新假數據。 而不是來自集合的反應數據。
到目前為止我有類似的東西:
// returns an object with a label and an array of timestamp, value
// like { label:'test', data:[[1397605016000, 1332],[1397605616000,1356],[1397606216000,1380]]}
Template.example.helpers({
readings: function(){
DataReadings.find();
}
});
Template.example.rendered = function() {
$.plot ($("#flot"), [this.data.data], {
series: {
lines: {
show: true
},
points: {
show: true
}
},
xaxis: {
mode: 'time',
timeformat: '%H:%M'
}
});
};
這適用於初始渲染,但不確定如何在新數據到達時更新圖表,大約每五分鍾一次。 那么當新數據到達時如何調用plot.setData(newData)&plot.draw()?
一種方法是使用游標/集合觀察器。 我在Meteor應用程序中使用此方法來更新Flot圖表並且效果很好。
在Template.example.rendered
函數中創建初始繪圖后,添加一個游標觀察器,只要在集合上添加(或刪除)新文檔,就會更新圖表:
// Subscribe to collection (or no need to do this if it's already done on your route)
Meteor.subscribe('dataReadings', someFilterVarOrNot);
// Add a cursor observer for all documents added with a date greater
// than right now (uses moment.js)
// (If you don't do this, you'll get an "added" fire for every document
// that's ALREADY been added - not sure why it does this but it does
dataReadingsObserveHandle = DataReadings.find({
createdAt: {$gte: moment().toDate()}}).observe({
// Fires anytime a new document is added
added: function(dataReading) {
$('#flot').data("plot").setData(dataReading.data);
$('#flot').data("plot").draw();
// Or setup whatever query/calculation you need to assemble a
// new data set for your chart, there are also some other observers like
// observeChanges() which let you see how a document has changed versus
// being added or removed
},
// Fires anytime a document is removed
removed: function(removedDataReading) {
// Update and redraw chart like above...
}
});
dataReadingsObserveHandle
是故意全局的,因此您可以稍后銷毀它,因為顯然集合觀察者是服務器密集型的。 如果您有需要銷毀的范圍訪問權限,則不一定必須是全局的:
// Once your chart no longer needs to be updated call...
dataReadingsObserveHandle.stop();
dataReadingsObserveHandle = null;
我相信當用戶導航到另一個模板並且不再查看您的圖表時,觀察者會自動被銷毀。 有關更多信息,請參見http://docs.meteor.com/#observe 。
我很想知道使用ReactiveVar
或Deps.dependency
執行此操作的其他方法。 特別是如果他們更有效率
我試過這種方法。 不完美的說得很簡潔
<template name="data">
<li> A : {{ A }}, B : {{ B }}
<div id="ph_{{A}}_{{B}}" style="width:100%;height:100px;" ></div>
{{ PlotMe this }}
</li>
</template>
和
Handlebars.registerHelper("PlotMe", function(element) {
setTimeout( function()
{
$.plot( "#ph_"+ element.A+"_"+element.B , [element.data] ,
{xaxis: {mode: "time", },yaxis: {min: 0, }});
} , 1 );
});
setTimeout可以避免Flot關於div的維度的錯誤無效,因為尚未呈現。 使用新數據更新flot。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.