【问题标题】:How to prevent Meteor.js Templates from rendering without data如何防止 Meteor.js 模板在没有数据的情况下呈现
【发布时间】:2012-10-30 01:24:24
【问题描述】:

有人可以帮我理解 Meteors 模板的行为吗?

我想在我的项目中实现一个通知系统,类似于 Apples Growl。 当一条记录写入数据库时​​,它使用简单的 jQuery 效果来显示一条消息。我已经简化了代码示例,以显示基本问题:

代码:

var Messages = new Meteor.Collection("messages");

if (Meteor.isClient) {
   Template.Notification.Message = function() {
     return Message.findOne({}, {sort: {seq: -1}});
   };

   Template.Notification.rendered = function() {
    $("#livebar").fadeIn(400).delay(1000).fadeOut(400);
   }
}

模板:

<template name="Notification">
<div class="row">
   <div class="span6 alert alert-error" id="livebar" style="display:none;">
        {{Messages.text}}
   </div>
</div>
</template>

如果页面被渲染,一个空的不可见区域会被 jQuery 效果渲染,然后系统加载响应数据源(消息)并再次渲染该区域! 我试图阻止它渲染两次,但没有成功。该错误似乎很容易修复,但我被困在这里。我将不胜感激!

【问题讨论】:

  • 试试 template.templateName.created 和 Meteor.defer

标签: javascript jquery twitter-bootstrap meteor


【解决方案1】:

你需要这个额外的代码:

首先在项目内部的终端上执行meteor remove autopublish

第二次定义要发布的内容

//On isServer
Meteor.publish('messages', function(){
    return Messages.find();
});

然后订阅该数据并等待其准备就绪

//On isClient
subscription_handle = Meteor.subscribe('messages');

Meteor.autorun( function(computation) {
    if( subscription_handle.ready() ) {

        //The data is now ready, start your templates here

        computation.stop(); //Stop autorun
    } 
});

另外,将您的集合定义为 var Messages = new Meteor.Collection("messages");,因此它是一个全局变量。

一种完全不同(但更简单)的方法是在 Iron Router 中使用模板路由的 waitOn 属性,这样您的模板会在数据准备好后呈现。

【讨论】:

  • 是的!在渲染之前必须确保订阅已准备好。救命稻草!
【解决方案2】:

您可以用{{#if}} 块包围模板调用{{&gt; Notification}}

{{#if has_notifications}}
  {{> Notifications}}
{{/if}}

//JS
Template.foo.has_notifications = function() {
  Message.find().count() > 0;
}    

但是由于数据不是以一体的形式到达的,因此可能会发生多次渲染模板的情况。超时可以帮助你...

【讨论】:

  • 感谢您提供此解决方法,它可以完成工作!它更简单:&lt;template name="Notification"&gt; {{#if Messages}} &lt;div class="span6 alert alert-error" id="lifebar" style="display:none;"&gt; {{Messages.text}} &lt;/div&gt; {{/if}} &lt;/template&gt; 它仅在加载数据源后呈现模板。
  • {{#if Messages}} 是助手还是通过这种方式调用meteor 来检查Messages-collection 中是否存在元素?
  • 你说得对,我指的不是“消息”,而是“Template.Notification.Message”助手,它已经可用于此模板。因此,它应该是{{#if Message}}
猜你喜欢
  • 2021-01-02
  • 1970-01-01
  • 2013-09-18
  • 2013-06-21
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多