2017-02-21 48 views
0

我有一個幫助函數返回一個數組,而不是傳統的db.dbName.find()遊標。我如何編碼一個return array,以便它反映爲一個類似於我可以在模板中使用的db.dbName.find()生成的光標?如何返回一個數組/值作爲遊標可以在我的模板中使用?

找到我下面的輔助函數:

var arrayTest = Meteor.call('getUserCategoryArray', function(error, results){ 
    if(error){ 
     console.log(error.reason); 
    } else {   

    var results1 = results.toString(); 
    var results2 = results1.split(","); 
    alert("Array content: " +results2); 
    alert(results2[0]); 
    alert(results2[1]); 
    alert(results2[2]); 

    return results2; 

    } 
}) 

爲了解釋的部分代碼:從自上而下:警報成功地打印出:

Array content: shoes,clothes,watches 

shoes 

clothes 

watches 

警報就是確認結果2是一個工作陣列。 現在我該如何編碼返回值/數組,以便能夠在我的模板中使用它,就好像它是由db.dbName.find()查詢返回的遊標一樣?

您的幫助表示讚賞。

+0

您可以將數組傳遞給#each手柄。 簽出[示例這裏](http://stackoverflow.com/questions/21234947/meteor-handlebars-how-to-access-a-plain-array) – mutdmour

+0

@mutdmour謝謝,但我不明白如何將它應用於我的代碼。我在我的模板中試過這個:{{#each results2}} \t {{this}} {{/ each}}'似乎沒有工作。我也嘗試過幫助函數名稱:allCategorie,所以在模板中,我嘗試了{{#each allCategories}} \t {{this}} {{/ each}}'。仍然沒有工作。任何幫助表示讚賞 – SirBT

回答

1

你的問題不是關於數組,而是關於同步和異步編程。正如@mutdmour所提到的,空格鍵可以很好地處理輔助數組中的數組。

助手可以在模板呈現時多次調用,所以它不應該做任何異步或有任何副作用。你的幫手正在做一個異步調用,所以這是一個問題。

您所看到的問題是這樣的調用是異步的,並且助手需要同步。所以你無法讓你的幫手按原樣工作。

在許多情況下,幫助程序將集合的內容或光標返回到集合的內容。我不知道你的應用,但發佈/訂閱收藏內容是一個更好的選擇嗎?

如果沒有,並且它必須是從一個方法調用的結果的話,一般我將:

  1. 使在onCreated()調用
  2. 將結果寫入到反應性變種
  3. 返回來自幫手的反應性變量

例如

Template.Foo.onCreated(function() { 
    let self = this; 
    self.clothing = new ReactiveVar(); 

    Meteor.call('getUserCategoryArray', function(error, results) { 
     if (!error) { 
      // or whatever you need to do to get the results into an array 
      self.clothing.set(results); 
     } 
    }); 
}); 

Template.Foo.helpers({ 
    clothing() { 
     return Template.instance().clothing.get(); 
    } 
}); 
相關問題