Meteor - 新列表条目的增量计数器:

Meteor - Increment counter on new list entry:

我正在做一个小项目,允许用户输入列表,然后遍历列表,测量在每个列表项上花费的时间。目前我无法识别单独的列表元素以单独分配它们,增量函数应该为每个列表条目添加一个唯一的 ID 但它似乎冻结在第一个列表项上并无限期地增加。任何人都建议为什么会出现这种情况或更好的解决方案? (请见谅Javascript)谢谢!

HTML:

<body>
<ul>
        {{#each travellists}}
            {{> travellist}}
        {{/each}}   
</ul>
</body>

<template name="travellist">
    <li style="list-style-type: none;" class = "{{selectedClass}}">
        <button class="delete">&times;</button>
        {{text}}
        <div>{{increment}}</div>
        {{#if isTrue}}
        <div class="timer"> {{listtime}} </div>
        {{/if}}
        </li>   
</template>

而 javascript 是:

Template.travellist.helpers({
        //return time elapsed for list item
        'listtime': function(){
            return runtime=((timer.time.get()/1000)%10).toFixed(2);
        },
        //change class name of selected item
        'selectedClass': function(){
            var listid = 0;
            listid++;
            return listid;          
        },
        //increment session counter and return value for list
        'increment': function(){
            Session.set("counter", Session.get("counter")+1);
            return Session.get("counter");
        },
    });

这里的问题是 increment 助手依赖于反应式会话变量计数器,所以每次 counter 改变时 increment 重新运行,这导致它无限增加,因为 counterincrement 助手内部发生变化。

您最好删除以下行:

Session.set("counter", Session.get("counter")+1);

并仅映射 travellists 以包含索引字段。例如,如果 travelists 被 return 编辑为名为 myCursor 的游标,那么 return 将 myCursor 编辑为 return:

myCursor.map(function(currentDoc, index, thisCursor){
    currentDoc.index = index;
    return currentDoc;
}

现在,在遍历 travellists 时,调用 {{index}} 将 return 此文档的索引。