流星js模板助手导致页面首次加载时出错



我有一个集合,由服务器发布,由客户端订阅,页面上显示一个模板助手。这一切都很好,但每次我刷新页面时,因为订阅取决于登录用户的userId,它看起来就像是在浏览器知道用户登录之前先运行代码一样(我认为是?),因此返回错误。

我的代码:

// on the server
Meteor.publish('reputation', function() {
  return Reputation.find({userId: this.userId});
});
// on the client
Reputation = new Mongo.Collection('reputation');
Router.configure({
  layoutTemplate: 'layout',
  loadingTemplate: 'loading',
  notFoundTemplate: 'notFound',
  waitOn: function() { 
    return [Meteor.subscribe('reputation')];
  }
});

信誉模板:

<template name="reputation">
    {{#if reputationCount}}
    <li><a href="#"><span class="badge badge-inverse">{{reputationCount}}</span></a></li>  
    {{/if}}
</template>

和助手:

Template.reputation.helpers({
  reputationCount: function(){
    return Reputation.findOne({userId: Meteor.userId()}).reputation;
  }
});

第一次刷新时出现的错误:

模板帮助程序中出现异常:TypeError:无法读取属性未定义的"声誉"。。。

在这之后它就工作了,只是控制台中出现错误很烦人。我以为在路由器中使用"waitOn"功能就不会出现错误,但我认为我错过了一些明显的东西。

请尝试此帮助程序代码:

Template.reputation.helpers({
  reputationCount: function(){
    var rep = Reputation.findOne({userId: Meteor.userId()});
    return rep && rep.reputation;
  }
});

以下是对这种行为的一个很好的解释

最新更新