【问题标题】:Meteor: How to activate template's helper when a variable is setMeteor:设置变量时如何激活模板的助手
【发布时间】:2015-09-15 18:02:33
【问题描述】:

我有这个助手:

Template.showScannedData.helpers({
    'lastConnectionNetId': function(){ 
        return Connections.findOne().netId; 
    }
});

与以下模板相关:

<template name="showScannedData">
    {{#if lastConnectionNetId}}}
       my last connection's id: {{lastConnectionNetId}}<br>
    {{/if}}
</template>

问题是,直到我没有真正向 Connections 集合添加一些东西(这是在 Cordova 中完成的,通过从 NFC 标签中获取一些数据然后将其存储在 MongoDB 中),我得到以下例外:

模板助手中的异常:TypeError:无法读取未定义的属性“netId”

我了解该异常是由于模板在数据可用之前激活造成的。

为了向用户“隐藏”问题(即不显示不完整的 UI),我在模板中添加了一个检查

如果 lastConnectionNetId

这是正确的做法吗?

如果集合为空,如何避免出现异常?

【问题讨论】:

    标签: meteor


    【解决方案1】:

    您应该查看我之前的评论here,您需要等待数据加载。

    另外,如果您仍然不确定是否有任何数据在收集中,您应该创建帮助器,例如:

     'lastConnectionNetId': function(){ 
       return Connections.findOne() && Connections.findOne().netId; 
     }
    

    更多有关 Meteor 防御性编程的信息,请访问here

    【讨论】:

      【解决方案2】:

      在你的情况下,findOne 返回一个对象。如果没有文档满足查询,则该方法返回 null。这意味着您的对象将是空的并且 netId 将是未定义的。我会试试这个:

      Template.showScannedData.helpers({
          'lastConnection': function(){ 
              return Connections.findOne(); 
          }
      });
      
      <template name="showScannedData">
          {{#if lastConnection}}}
             my last connection's id: {{lastConnection.netId}}<br>
          {{/if}}
      </template>
      

      这可以解决你的问题。

      【讨论】:

        猜你喜欢
        • 2015-03-28
        • 2016-06-10
        • 2015-01-06
        • 2015-01-10
        • 2014-11-27
        • 2013-02-18
        • 2014-05-02
        • 2010-11-26
        • 2015-09-30
        相关资源
        最近更新 更多