您是对的,您应该确保在正确加载数据后执行依赖于获取客户端订阅集合内容的代码。
您可以使用 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>
在空格键模板声明中,我们使用封装outer 模板来处理模板级订阅模式。
我们在 onCreated 生命周期事件中订阅发布,并且我们使用特殊的响应式帮助器 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 日:修改了答案,因为它包含过时的材料,但仍然收到了赞成票。