如何在渲染模板之前使用meteor subscriptionsReady()来确保数据准备就绪?

时间:2015-04-22 05:48:45

标签: javascript templates meteor iron-router meteor-collections

使用新的和正在开发的框架的挑战之一是您在网络上找到的建议经常过时。这对于Meteor来说是双重的,其中SO答案和网络文章通常用于1.0.x之前版本或早期1.0.x版本,或者用于之前版本的铁路由器,或者在他们上周引入功能之前,等等

仍然困惑如何在模板等待直到订阅准备就绪的上下文中使用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 ...
}

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

Iron路由器方式:

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>

流星方式:

  

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

第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>

答案 1 :(得分:0)

有等待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 docs

相关问题