如何使用流星订阅ready()来确保数据在渲染模板之前准备好



使用一个新的、正在开发中的框架的挑战之一是,您在网上找到的建议往往已经过时。这同样适用于Meteor,在Meteor中,SO的答案和网络文章通常是针对1.0.x之前或1.0.x早期版本,或之前版本的iron路由器,或在上周推出功能之前,等等

在让模板等待订阅准备好的情况下,如何使用subscriptionsReady()函数仍然令人困惑。我当然需要它,因为我的模板在大约3/4的时间里试图在没有数据的情况下渲染。

如何使用subscriptionsReady()?我见过在html中使用它的例子,我认为这有点愚蠢(模糊表示和函数)。如何在模板的代码部分使用它?

它用在有某种waitOn的铁路由器上吗?我是否在模板渲染器中使用while循环来包装它?你能举一个简单的例子吗?

强制性代码内容。。。我的模板的路线:

Router.route('/', {
path: '/',
template: 'navmenu',
onBeforeAction: function() {
this.next();
}
});

我的订阅:

// Chapters
ChapterCollection = new Mongo.Collection("ChapterCollection");
if(Meteor.isClient){
Meteor.subscribe('users');
Meteor.subscribe('roles');
Meteor.subscribe('ChapterCollection');
}

html部分非常简单,一些html封装在一个模板标记中。

我的模板代码:

Template.navmenu.rendered = function() {
// Load all chapters from collections
// Unless it decides to delay and then we are *%&@ed
chapterArray = ChapterCollection.find().fetch();
... other stuff ...
}

谢谢你的帮助。

铁路由器方式:

Router.route('/', {
name: 'nameOfRoute',
waitOn: function () {
// we will wait for these subsciptions
return [Meteor.subscribe('users'), Meteor.subscribe('roles'), Meteor.subscribe('ChapterCollection')]
},
action: function () {
// this.ready() is true if all items in the wait list are ready
if (this.ready()) {
this.render('yourTemplate');
}
else {
// if not ready, you can render another template in the meantime.
this.render('Loading');
}
}
});

action函数中,您还可以创建模板辅助对象。例如,如果waitOn函数中的某个订阅从名为ChapterCollection的集合返回文档,则名为helperA的帮助程序将把这些数据传递给模板:

if (this.ready()) {
this.render('yourTemplate', { data: {helperA: ChapterCollection.find()} });
}

html:

<template name="yourTemplate">
//use the #each or #with block with respect to the data being returned. E.g
{{#each helperA}}
{{fieldName}}
{{/each}}
</template>

流星方式:

您可以使用this.subscribe从onCreated回调指定此模板依赖于的数据发布

步骤1:

因此,一个简单的逐步解释:一旦创建了模板,就会调用这些订阅。请注意,这是我们在步骤2中的模板中所做的操作。阻止"内容"呈现,直到订阅准备就绪

Template.yourtemplate.onCreated(function () {
this.subscribe("users");
this.subscribe("roles");
this.subscribe("ChapterCollection");
});

步骤2:

<template name="yourTemplate">
{{#if Template.subscriptionsReady}}
// all of the template contents here will be rendered ONLY when the subscriptions within the onCreated callbacks are ready.
{{else}}
// if subsciption is not ready, you may show something else here. E.g. "Loading...."
{{/if}}
</template>

Iron Router中有等待订阅的waitOn方法:

Router.route('/', {
name: 'navmenu',
waitOn: function() {
return [
Meteor.subscribe('users');
Meteor.subscribe('roles');
Meteor.subscribe('ChapterCollection');
];
},
onBeforeAction: function() {
this.next();
}
});

因此,您可以在客户端代码中删除订阅。

您的"模板"选项应该是"名称"。阅读Iron Router文档。

最新更新