【问题标题】:meteor js - template helper causing errors when page first loads流星 js - 模板帮助程序在页面首次加载时导致错误
【发布时间】:2015-05-04 01:46:52
【问题描述】:

我有一个由服务器发布、由客户端订阅的集合和一个显示在页面上的模板助手。这一切都很好,但是每次我刷新页面时,因为订阅取决于登录用户的 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”功能,它不会给出错误,但我认为我错过了一些明显的东西。

【问题讨论】:

  • 也尝试使用 #if currentUser 代替 #if 信誉计数,但仍然相同...

标签: javascript meteor


【解决方案1】:

请改用这个帮助代码:

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

这是nice explanation of this behavior

【讨论】:

  • 效果很好!并感谢您的链接,非常有意义,它是“我应该知道”的解决方案之一:-)
猜你喜欢
  • 2013-06-05
  • 1970-01-01
  • 2013-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-03
  • 2019-05-27
相关资源
最近更新 更多