javascript - 在下一步之前等待 meteor 收集完成

标签 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
};

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

Deps afterFlush 函数异常:类型错误:无法读取未定义的属性“日期”

我没有在任何情况下使用 Deps。据我了解,该集合在完全加载完成之前被引用。

因此,我想弄清楚如何简单地说“等到找到集合后再继续”。应该很简单,但找不到更新的解决方案。

最佳答案

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

您可以使用 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");
});

client/views/svg/svg.html

<template name="outer">
  {{#if Template.subscriptionsReady}}
    {{> svgTemplate}}
  {{else}}
    Loading...
  {{/if}}
</template>

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

Template.svgTemplate.onRendered(function(){
  console.log(Pushups.find().fetch());
});

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

将包添加到您的项目中:

meteor add iron:router

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(/*...*/);
  }
});

使用这段简单的代码,您将获得您想要的以及许多附加功能。 您可以查看 Iron Router 指南,其中详细解释了这些功能。

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

2015 年 3 月 18 日编辑:修改了答案,因为它包含过时的 Material ,但仍然收到了赞成票。

关于javascript - 在下一步之前等待 meteor 收集完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20942025/

相关文章:

javascript - 在公共(public)变量中获取不同的html元素

javascript - Firebase Auth 检查 Facebook 上的新用户是否登录

css - Meteor Bootstrap 节点模块覆盖我自己的 css

reactjs - React/Apollo - 不同组件中的类似查询?

javascript - 使用 if 在 Meteor.js 的不同页面上有不同的元素

javascript - 使用 Meteor 监听 Webhook 服务器端

javascript - 通过收集迭代时的 meteor 延迟

javascript - HTML 表格中的居中文本

javascript - 在 JS 数组中使用命名键

javascript - 在模糊/焦点事件上使用 $validators