如何在客户端Collection增长时立即反应性地执行代码
How to reactively execute code as soon as a client Collection grows?
我正在努力跟踪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
。
相关文章:
- setTimeout函数能否在其前面的代码执行之前激发
- 延迟代码执行,直到下载完成
- 奇怪的javascript代码执行顺序
- 将字符串作为一段 HTML/javascript 代码执行
- 使用AngularJS,如何在视图和控制器同步特定更改后触发代码执行
- onKeyUp 导致代码执行两次
- JQuery:将参数传递给插件以限制代码执行
- JavaScript代码执行时间
- 基本的JavaScript代码执行
- JavascriptCore:从本机代码执行JavaScript定义的回调函数
- 脚本标记的位置会影响代码执行
- 页面脚本未使用 Salesforce Web-to-Lead 代码执行
- GM_xmlhttpRequest 成功回调“onload”未为注入的代码执行
- 停止所有代码执行,直到 IFrame 完全加载
- 纯 Javascript 代码执行停止混合应用程序中的离子加载指示器
- Javascript代码执行顺序
- Javascript:在嵌套函数中使用条件语句停止代码执行
- Node.js代码执行顺序
- 什么触发JavaScript代码执行
- onreadystatechange导致php代码执行两次