Each loop not updating in html

Hey everyone,

I have a problem with a pretty basic setup.

I have two files, tags.html and tags.js

tags.html:

{{#each mytags}}
<span class="btn btn-info">{{this}}</span>
{{/each}}
<input type="text" placeholder="Enter Tag Here" id="enterTag">

tags.js:

tagslist = ['tag1', 'tag2'];
Template.tags.helpers({
    'mytags': function(){
        return tagslist;
    }
});
Template.tags.events({
    'keypress input#enterTag': function(event){
        if (event.which === 13)
        {
            var tag = (event.target).value;
            tagslist.push(tag);
            console.log(tagslist);
            $('#enterTag').val('');
        }
    },

The problem is the each loop doesn’t react and update with the new element when the array gets updated. I can see the array in the console having the new values pushed, but the each loop has doesn’t load those new values.

What could I be missing? This looks like it should be pretty straight forward.
I will note that this is all happening within a modal.

The keyword in your question were “the each loop doesn’t react”. The simple array you are using to hold your data is not a reactive datasource, so Meteor does not know to update your each loop.

Check out the guide or docs for reactive programming

1 Like

You’re right, I didn’t recognize the significance of the reactive environment necessary for Meteor to operate the way we need it to. I will study it further, however for the sake of time, I did a quick google search and found the following

Looks like this will accomplish what I wanted. Luckily I’m not the only person to have this demand.

Thanks!

You don’t need that package necessarily (it adds bloat imo), just use new ReactiveVar().

Quick example (check it as I just wrote it by heart):

Template.tags.onCreated(function(){
    var t = this;

    t.tagslist = new ReactiveVar(["tag1", "tag2"]);
});

Template.tags.helpers({
    "mytags": function(){
        return Template.instance().tagslist.get();
    }
});

Template.tags.events({
    "keypress input#enterTag": function(e, t){
        if(e.which === 13){
            var tag = (e.target).value;
            t.tagslist.set(t.tagslist.get().push(tag));
            console.log(t.tagslist.get());
            $("#enterTag").val("");
        }
    },
});