小编Dre*_*erz的帖子

Meteor:Tracker.autorun/observeChanges&collections无法按预期工作

我是使用meteor的新手,所以我希望得到一个关于这些功能如何工作的基本解释,以及我应该如何使用它们.否则,如果有一种方法更适合我希望实现的目标,那么我们将不胜感激.

我希望实现的功能:

我有一个Mongo集合,其中包含分配给特定用户的文档中的数字值.

我将使用从文档中获取的值来填充宽度:在'progressbar'上的某些css内联样式中使用xx%.但我使用的其他用途是执行某种"反应"功能,该功能在此值发生变化时运行,可以根据进度条的当前值动态更新此进度条的背景颜色.认为"红色"为低,"绿色"为高:

project.html:

<template name="progressBar">
  <div id="progress-bar" style="width:{{curValue}}; background-color:*dynamicColor*;"></div>
</template>
Run Code Online (Sandbox Code Playgroud)

project.js:

Progress = new Mongo.Collection("progress");

Template.progressBar.helpers({
  curValue: function () {
    return Progress.findOne({user: Meteor.userId()}).curValue;
  }
});
Run Code Online (Sandbox Code Playgroud)

以上有时会起作用.但它似乎并不可靠,现在对我不起作用.我得到的错误无法读取未定义的属性'curValue'.根据我在网上研究的内容,这意味着我在加载集合之前尝试访问此文档.但我真的找不到一个直接的解决方案或围绕我应该如何构建这个以避免该错误.

下一个问题是观察对该值的更改并运行一个函数来更改背景颜色(如果它确实发生了变化).

以下是我尝试过的一些自动运行/观察代码类型:

Session.set('currentValue', Progress.findOne({user:Meteor.userId()}).curValue);
Tracker.autorun(function(){
  var currentValue = Session.get('currentValue');
  updateColor(currentValue);
});

var currentValue = Progress.findOne({user:Meteor.userId()}).curValue);
var handle = currentValue.observeChanges({
  changed: function (id, currentValue) {
    updateColor(currentValue);
  }
});
Run Code Online (Sandbox Code Playgroud)

总结问题/问题:

我想在某些内联css中使用mongo db文档中的值,并跟踪该值的更改.当值改变时,我想要一个运行的函数来更新div的背景颜色.


更新

使用@Ethaan的答案,我能够纠正我的收集数据的订阅/模板使用情况.我做了一些挖掘,并对发布/订阅方法有了更深入的了解,并学习了如何在我的集合加载后的适当时间正确使用订阅上的回调来运行我的Tracker.autorun函数.我能够扩展下面给出的答案,包括一个反应性Tracker.autorun,它将运行一个函数,让我根据我的文档值更新我的颜色.

我最终得到的代码如下:

project.js

if (Meteor.isClient) {

  Progress = new Mongo.Collection("progress");

  Template.content.onCreated(function () {
    var self = this;

    self.autorun(function () {
      self.subscribe("progress", …
Run Code Online (Sandbox Code Playgroud)

javascript css mongodb meteor meteor-helper

3
推荐指数
1
解决办法
6833
查看次数

标签 统计

css ×1

javascript ×1

meteor ×1

meteor-helper ×1

mongodb ×1