[英]Meteor findOne query returns undefined in one template helper. In other template helpers, same query works well
假設我有一個名為GameStatus
的Meteor集合。 我有不同角色的用戶,但我為所有用戶發布了GameStatus集合。 我只是在server / publications.coffee中使用以下內容
Meteor.publish 'gamestatus', ->
GameStatus.find()
對於兩個角色('S'和'B'),當我使用以下模板助手(在文件client / views / seller.coffee和client / views / buyer.coffee中定義)時,我沒有問題。
currentRound: ->
return GameStatus.findOne().currentRound
對於這些我永遠不會得到以下錯誤。
Uncaught TypeError: Cannot read property 'currentRound' of undefined
但是對於另一個角色('admin'),使用相同的模板助手(在文件client / views / admin.coffee中定義)給出了上面顯示的Uncaught TypeError。 如果我改為寫,它可以工作:
currentRound: ->
return GameStatus.findOne()?.currentRound
我有點理解為什么會這樣。 我認為,在加載頁面時,該集合首先不可用,然后就可以使用了。 但為什么上面顯示的其他模板不會發生這種情況?
如果有人可以幫助澄清這一點,我們將非常感激。
我確信收集准備好的時候並不總是一致的,所以如果你想要涵蓋所有基礎,請始終為未准備好收集的情況編寫代碼。
處理未准備好的集合有一種快速而骯臟的方法,以及您可以在todos示例中找到的更復雜的解決方案。
快速而骯臟的解決方案看起來像這樣。
currentRound: ->
gameStatusrecord = GameStatus.findOne();
if(gameStatusRecord)
gameStatusRecord.currentRound
這會奏效。 在集合准備好之前,currentRound將返回null,並且您的模板將短暫呈現,並且可能只顯示當前輪次的空白。 所以不是理想的用戶體驗,但不是很大的交易。
對於更復雜的解決方案,您可以使用“就緒”功能檢查您訂閱的集合是否已准備好進行查詢。 如果集合尚未就緒,您可以渲染其他模板,例如“loading”,這樣可以保證在集合准備好之前不會調用currentRound助手。
例如,在todos示例中,客戶端訂閱了todos.js第24行的“lists”集合:
var listsHandle = Meteor.subscribe('lists', function () {
然后在todos.js的第80行上為列表模板定義一個輔助函數
Template.lists.loading = function () {
return !listsHandle.ready();
};
然后在todos.html第20行的列表模板中,除非listsHandle准備就緒,否則它不會嘗試呈現任何模板。
<h3>Todo Lists</h3>
{{#if loading}}
<div id="lists">Loading...</div>
{{else}}
<div id="lists">
{{#each lists}}
<!--etc.-->
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.