2014-09-10 52 views
0

我想在Meteor JS helper函數中使用jQuery來計算表兒童的位置,但我總是得到一個空結果,因爲輔助函數在插入表數據之前返回。爲幫助函數減緩流星頁面渲染

這裏是我的代碼:

<table class="table"> 
       <thead> 
       <tr> 
        <th>#</th> 
        <th>Game</th> 
       </tr> 
       </thead> 
       <tbody> 
        {{#each games}} 
         {{> game}} 
        {{/each}} 
       </tbody> 
</table> 


    <template name="game"> 
     <tr> 
      <td>{{counter}}</td> 
      <td>{{name}}</td> 
     </tr> 
    </template> 

Template.game.helpers({ 
    counter: function() { 
     return $('table.table tbody tr td:contains("this.name")').index(); 
    } 
}); 

應該是這樣: 1測試 2 ABC 3的HelloWorld ...

任何幫助將不勝感激。

+1

如何要渲染該表?你的選擇器似乎無效,試試這個:'返回$('table.table tbody tr td:contains(''+ this.name +'「)')。index();' – 2014-09-10 18:52:52

+0

謝謝你的幫助!但是現在我得到1每個條目,它應該按降序排列。是否有可能通過'index()'來實現呢? – user3475602 2014-09-10 18:59:08

+0

沒有看到代碼的其餘部分,很難說。使用像這裏這樣的jQuery技巧來操作數據會更好。請告訴我你如何生成表格(模板,路線,數據)? – 2014-09-10 19:04:01

回答

3

解決方案的想法是,您將添加到遊戲對象數組中的其他字段稱爲index。 稍後在game模板中,您只需使用{{index}}

下面的代碼應該解決您的問題:

var games_with_index = Games.find().map(function(document, index){ 
    document.index = index; 
    return document; 
}); 

<table class="table"> 
    <thead> 
     <tr> 
      <th>#</th> 
      <th>Game</th> 
     </tr> 
    </thead> 
    <tbody> 
     {{#each games_with_index}} 
      {{> game}} 
     {{/each}} 
    </tbody> 
</table> 

<template name="game"> 
    <tr> 
     <td>{{index}}</td> 
     <td>{{name}}</td> 
    </tr> 
</template> 

參見本: Print the loop index in Meteor.js templates