Meteor更新flot图表

3
当使用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'
    }
  });
};

这对于初始渲染非常有效,但是不确定如何在新数据到达时更新图表,每5分钟左右会有一次。那么当新数据到达时如何调用plot.setData(newData)和plot.draw()呢?

看一下Deps包 - 或者Tracker(Meteor 0.9) - Adam Wolski
2个回答

1

一种方法是使用游标/集合观察器。我在我的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
我很想了解使用ReactiveVarDeps.dependency进行此操作的其他方法。特别是如果它们更有效。

0
我尝试了这种方法。不完美但相当简洁。
<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 已使用新数据进行更新。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接