2015-03-31 64 views
1

我是Meteor的初學者,無法完成迭代集合並將每個項目的單個屬性打印到模​​板的簡單任務。我打開了自動發佈功能,所以我沒有編寫發佈/訂閱功能。到目前爲止,我所做的其他所有組件都能正常工作,所以我很確定問題出在下面的代碼中。無法遍歷集合並插入到模板中

在HTML(注意評論)

<template name="tags"> 
    <div class="tags"> 
      {{#each printTags }} 
        {{name}} <br> 
      {{/each }} 
      <!-- why is nothing showing up here? --> 
    </div> 
    <template> 

在JS文件

if (Meteor.isClient) { 

     Tags = new Mongo.Collection("tags") 

     tags = Tags.find({}).fetch(); 

     Template.tags.helpers({ 
      printTags: tags 
     }); 
    } 

在客戶端,在開發工具

Tags.find().fetch().forEach(function(tag){console.log(tag["name"])}) 
    1 
    2 
    3 
    4 
    5 

回答

0

與您的代碼的問題是,你的printTags助手被分配給一個變量(tags),該變量持有取回的結果e收集文件尚未充滿數據時的收集文件。

必須使用一個函數,從而表達將是反應性地重新評估時數據是可用的:

Template.tags.helpers({ 
    printTags: function(){ 
    return Tags.find(); 
    } 
}); 
+0

這是不反應的,在調用.fetch()停止這一點。爲了使用db中的反應數據,你必須返回一個'''cursor''' http://docs.meteor.com/#/full/mongo_cursor – 2015-03-31 08:24:36

+0

你是對的,在這種情況下,返回一個遊標更合適Blaze可以優化#each只重新渲染其內容的一部分。但這不是你在一個觸發反應性的被動計算中返回的內容,它是被評估並最終依賴的被動數據源,所以即使你使用fetch返回一個普通數組,該幫助仍然會被動,因爲find調用會觸發任何反應。 – saimeunt 2015-03-31 08:54:30