【问题标题】:Waiting data while dynamically loading templates in Meteor.js在 Meteor.js 中动态加载模板时等待数据
【发布时间】:2015-09-29 20:18:21
【问题描述】:

在我的 meteor.js 应用程序中,我正在动态加载模板;

  {{#DynamicTemplate template=getTemplate data=getData}}
    Default content when there is no template.
  {{/DynamicTemplate}}

当我加载子模板时,是否可以等待渲染子模板,直到来自 getData 的子模板数据准备好?我的意思是我可以做类似铁路由器的 waitOn 功能吗?谢谢

【问题讨论】:

    标签: meteor iron-router


    【解决方案1】:

    您可以采取的一种方法是订阅模板的created 函数,然后在渲染模板时,首先检查每个订阅的ready(),如果它们不是全部正确,则渲染加载显示。

    <template name="templateWithSubscription">
      {{#if ready}}
        <!-- actual content -->
      {{else}}
        loading...
      {{/if}}
    </template>
    
    Template.templateWithSubscription.created = function () {
      this.subscriptions = [
        Meteor.subscribe(/* ... */),
        Meteor.subscribe(/* ... */),
        /* ... */
      ];
    };
    
    Template.templateWithSubscription.destroyed = function () {
      _.each(this.subscriptions, function (sub) {
        sub.stop();
      });
    };
    
    Template.templateWithSubscription.helpers({
      ready: function () {
        return _.all(Template.instance().subscriptions, function (sub) {
          return sub.ready();
        });
      }
    });
    

    类似的方法可用于其他数据源(例如方法)。

    【讨论】:

    • 如何进行多个订阅并在销毁时阻止它们?
    • 感谢您的快速回复
    • 这篇文章也很有帮助,特别是如果你想添加一个基于某些东西(例如分页)更新的动态数据上下文。 discovermeteor.com/blog/template-level-subscriptions
    【解决方案2】:

    您现在可以在模板中使用{{#if Template.subscriptionsReady}}

    Template.instance().subscriptionsReady() 在 js 代码中。当然你也可以使用this关键字作为对当前模板的引用。

    【讨论】:

      猜你喜欢
      • 2012-10-09
      • 2018-11-22
      • 2015-01-15
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2015-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多