2014-09-04 83 views
3

我添加了一个全局帮助函数,它带有返回一个字符串的UI.registerHelper。如果我访问特定的网站,我可以看到正确的输出,但我得到以下异常:在流星中使用全局助手的模板助手的例外

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'; 
}); 

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

回答

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的情况下茎(无找到)。您无法访问nullmode财产。

+0

谢谢!那做了这个工作。你认为我得到了正确的输出,因为页面被渲染了两次? – user3475602 2014-09-04 20:59:10

+1

它可能在“游戏”被填充之前渲染一次,并且一旦'Games.findOne'返回一个文档就会再次渲染一次。观察Iron Router和'waitOn'以避免不必要的第一次渲染。 – 2014-09-04 21:00:26

+0

感谢您的提示! – user3475602 2014-09-05 10:47:29

相关问题