一种方法是使用游标/集合观察者。我在我的 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
or的方法Deps.dependency
。特别是如果他们更有效率