在下一步之前等待流星收集完成

Mat*_*t H 12 javascript meteor

我有一个应该显示一些数据的Meteor模板.

Template.svg_template.rendered = function () {
  dataset_collection = Pushups.find({},{fields: { date:1, data:1 }}, {sort: {date: -1}}).fetch();

  a = moment(dataset_collection[0].date, "YYYY/M/D");
  //more code follows that is also dependent on the collection being completely loaded
};
Run Code Online (Sandbox Code Playgroud)

有时它有效,有时我得到这个错误:

来自Deps afterFlush函数的异常:TypeError:无法读取undefined的属性'date'

我在任何情况下都不使用Deps.据我了解,该集合在完成加载之前就被引用了.

因此,我想弄清楚如何简单地说"等到收集之后才能找到收集品".应该是直截了当的,但找不到更新的解决方案.

sai*_*unt 32

你是对的,你应该确保在正确加载数据之后执行取决于获取客户端订阅集合内容的代码.

您可以使用Meteor 1.0.4中引入的新模式实现此目的:https://docs.meteor.com/#/full/Blaze-TemplateInstance-subscribe

client/views/svg/svg.js

Template.outer.onCreated(function(){
  // subscribe to the publication responsible for sending the Pushups
  // documents down to the client
  this.subscribe("pushupsPub");
});
Run Code Online (Sandbox Code Playgroud)

client/views/svg/svg.html

<template name="outer">
  {{#if Template.subscriptionsReady}}
    {{> svgTemplate}}
  {{else}}
    Loading...
  {{/if}}
</template>
Run Code Online (Sandbox Code Playgroud)

在Spacebars模板声明中,我们使用封装outer模板来处理模板级订阅模式.我们在onCreated生命周期事件中订阅了该发布,并且我们使用特殊的反应帮助Template.subscriptionsReady程序仅svgTemplate在订阅准备就绪后呈现(数据在浏览器中可用).此时,我们可以安全地PushupssvgTemplate onRendered生命周期事件中查询集合,因为我们确保数据已经到达客户端:

Template.svgTemplate.onRendered(function(){
  console.log(Pushups.find().fetch());
});
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用iron:router(https://github.com/iron-meteor/iron-router),它提供另一种设计模式来实现此常见的Meteor相关问题,在路由级别而不是模板级别移动订阅处理.

将包添加到您的项目:

meteor add iron:router
Run Code Online (Sandbox Code Playgroud)

lib/router.js

Router.route("/svg", {
  name: "svg",
  template: "svgTemplate",
  waitOn: function(){
    // waitOn makes sure that this publication is ready before rendering your template
    return Meteor.subscribe("publication");
  },
  data: function(){
    // this will be used as the current data context in your template
    return Pushups.find(/*...*/);
  }
});
Run Code Online (Sandbox Code Playgroud)

使用这段简单的代码,您将得到您想要的内容以及许多附加功能.您可以查看Iron Router指南,其中详细介绍了这些功能.

https://github.com/iron-meteor/iron-router/blob/devel/Guide.md

编辑18/3/2015:重写了答案,因为它包含过时的材料,但仍然收到了赞成票.