2014-09-04 36 views
5

我正在努力學習流星,並且遇到了幾個障礙。我有幾個嵌套的模板來顯示所有的在我的應用程序的用戶信息:如何訪問數組中的Meteor用戶屬性?

users_list.html:

<template name='usersList'> 
    <div class='users'> 
    {{#each user}} 
     {{> userItem}} 
    {{/each}} 
    </div> 
</template> 

和user_item.html:

<template name='userItem'> 
    <div class='user'> 
    <div class='user-content'> 
     <h3>User:</h3> 
     <h4>Email: {{emails}}</h4> 
      <h5>ID: {{_id}}</h5> 
      ... 
    </div> 
    </div> 
</template> 

,關聯的模板幫助:

Template.usersList.helpers({ 
    user: function(){ 
    return Meteor.users.find().fetch(); 
    } 
}); 

這適用於頂級屬性,但如果我嘗試顯式訪問.addres通過改變上述行user_item.html的電子郵件數組中的0指數的財產:

<h4>Email: {{emails[0].address}}</h4> 

流星抱怨:

Exception in queued task: Error: Can't call non-function: [object Object]...

這是令人困惑我,因爲我可以在控制檯做到這一點:

var userz = Meteor.users.find().fetch(); 
userz[0].emails[0].address // "[email protected]" 

任何想法,爲什麼流星不喜歡這個?

此外,我一般在想,我可能需要將電子郵件數組的內容存儲到變量中,並重覆上述相同的模式,除了將emails_list和email_item模板嵌套到user_item模板中。這似乎是可行的,但對於這個用例過於複雜。

最終,我只是試圖學習和實現一個合理的模式來訪問和顯示集合中文檔的嵌套屬性。任何想法或指導將不勝感激。

回答

6

這僅僅是一個與你的語法問題,試試這個:

<h4>Email : {{emails.[0].address}}</h4> 

您需要訪問使用點語法的電子郵件數組的第一個元素(一個屬性,它的關鍵是「0」)。

https://github.com/meteor/meteor/wiki/Using-Blaze#dotted-helpers-with-numeric-indices

您也可以使用這個模式來顯示電子郵件的列表:

(from userItem) 
{{> emailsList}} 

<template name="emailsList"> 
    <ul> 
    {{#each emails}} 
     {{> emailItem}} 
    {{/each}} 
    </ul> 
</template> 

<template name="emailItem"> 
    <li>Address : {{address}}</li> 
</template> 

我不認爲這是過於複雜(只是一對夫婦更多的模板),並與該流星很容易做到。 只要合理,將您的模板切片到更多的子模板中,就可以簡化和加速DOM重新渲染數據失效。

另外,在助手中返回遊標時,不需要使用fetch:#each塊經過優化,可直接使用遊標而不是數組。 (它將足夠聰明,只需重新渲染修改後的項目而不是整個列表)。

+0

這工作流星,謝謝。但是,此代碼在控制檯中不起作用。我的JavaScript今天關閉了嗎?我不明白爲什麼我們需要。符號來獲取郵件數組0索引處的項目。 – Chris 2014-09-04 22:00:59

+0

這是因爲Spacebars(流星實現把手的)東西從JavaScript不同的是,你的語法是爲JS確定的,但錯誤的模板引擎。 – saimeunt 2014-09-04 22:03:55

+0

@walter連接到我的災難的來源。謝謝您的幫助 – Chris 2014-09-04 22:11:11

1

你可以檢查火焰

文件對於顯示陣列中的模板,必須寫這樣顯示的文檔,

在虛線助手,圍繞數字索引,例如使用括號{{ currentUser.emails。[0]。地址}}代替{{currentUser.emails.0.address}}

Good {{currentUser.emails.[0].address}}


Bad {{currentUser.emails.0.address}}

維基

https://github.com/meteor/meteor/wiki/Using-Blaze