Meteor - Increment counter on new list entry:

- 1 answer

Ad

I'm working on a small project that allows user input to a list, and then iterates through the list, measuring the time spent on each list item. At the moment I'm having trouble identifying the individual list elements to assign them individual times, the increment function is supposed to add a unique ID to each list entry but it seems to freeze on the first list item and increment indefinitely. Anyone got a suggestion why this might be the case or a better solution? (Please excuse awful Javascript) Thanks!

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>

And the javascript is:

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");
        },
    });
Ad

Answer

Ad

The problem here is that the increment helper depends on the reactive session variable counter, so each time counter is changed increment reruns which is causing it to increment indefinitely since counter is changing inside the increment helper.

You would be better off to remove the line:

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

and to just map travellists to include an index field. For example, if travelists is returned as a cursor called myCursor, then instead of returning myCursor, return:

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

Now, while iterating over travellists, calling {{index}} will return the index of this document.

Ad
source: stackoverflow.com
Ad