模板助手中使用Meteor中的全局助手的例外情况

时间:2014-09-04 20:42:39

标签: javascript meteor

我在UI.registerHelper中添加了一个全局辅助函数,它返回一个String。如果我访问特定网站,我可以看到正确的输出,但我得到以下异常:

Exception in template helper: http://localhost:3000/client/helpers/global_helpers.js?c1af37eca945292843a79e68a3037c17a0cfc841:18:45
http://localhost:3000/packages/blaze.js?cf9aea283fb9b9d61971a3b466bff429f9d66d7d:2458:21

这是我的代码:

UI.registerHelper('levelMode', function() {
    return Games.findOne({_id: this._id}).mode ? 'Difficult' : 'Easy';
});

有任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

尝试添加一些支票:

UI.registerHelper('levelMode', function() {
  if (typeof Games !== 'undefined' && Games != null)
    var game = Games.findOne({_id: this._id});
    if (game != null && game.mode)
      return 'Difficult';
  return 'Easy';
});

我的预感是,错误源于尚未定义游戏的情况(模板在定义集合之前呈现)或findOne返回null(未找到任何内容)。您无法访问mode的{​​{1}}属性。