如何在客户端Collection增长时立即反应性地执行代码

How to reactively execute code as soon as a client Collection grows?

本文关键字:代码 执行 客户端 Collection      更新时间:2024-03-01

我正在努力跟踪Meteor中某个电抗值的增量。如果当前值增加了1或更多,我希望发生一些事情。我确实有两个问题:

  • 首先:我不知道如何对这个函数进行if语句
  • 第二:我不知道如何才能跟踪增长

这是我现在使用Mongo.Collection cars(来自API)的代码:

api = DDP.connect('url');
const currentCars = new Meteor.Collection('cars', api);
const newCars = cars.find().count()
if (Meteor.isClient) {
  Template.currentCars.helpers({
    carsInCity: function() {
      return currentCars.find(
      {
        location: "city"
      }).count();
    },
  })
}

因此,这个城市目前有大量的汽车。每次多一辆车的时候,我都希望代码中发生一些事情。但我到底该怎么做呢?也许是通过跟踪数据库何时更新?

一个相当直接的解决方案是将当前数据量存储在该集合中,然后运行反应式计算,看看是否有任何变化。

类似这样的东西:

let currentCarsCount = cars.find().count()
Tracker.autorun(function checkForAddedCars() {
  // cars.find() is our reactive source
  const newCarsCount = cars.find().count()
  if(newCarsCount > currentCarsCount) {
    currentCarsCount = newCarsCount
    // There's new cars, handle them now
    // ...
  }
})

您可能还想使用模板级别autorun,这样就不必管理停止checkForAddedCars。您还可以将currentCarsCount作为一个状态存储在模板实例上,而不是作为一个提升的孤独者。

例如:

Template.currentCars.onCreated(function() {
  const templateInstance = this;
  // equivalent:
  const templateInstance = Template.instance();
  templateInstance.currentCarsCount = cars.find().count();
  templateInstance.autorun(function checkForAddedCars() {
    // cars.find() is our reactive source
    const newCarsCount = cars.find().count();
    if(newCarsCount > templateInstance.currentCarsCount) {
      templateInstance.currentCarsCount = newCarsCount;
      // There's new cars, handle them now
      // ...
    }
  });
});

它还允许您从模板代码中的其他位置访问currentCarsCount