Tabrez Ahmed
Tabrez Ahmed

Reputation: 2950

Template.autorun() and Tracker.afterFlush() not working

From what I could understand from the official docs, function passed as parameter to template.autorun should run whenever there is an update in the DOM.

But I don't find it happening.

//dummies.html
<template name="dummies" >
    {{#each dummies}}
        {{this.count}}&nbsp;
    {{/each}}
</template>

//dummies.js
Template.dummies.onRendered(function(){
    var counter = 0;
    setInterval(function(){
        Dummies.insert({count: counter++})
    }, 2000);
    this.autorun(function(){
        console.log("From autorun:", Dummies.find().count()) //--->Line1
        Tracker.afterFlush(function(){
            console.log("From afterFlush:", Dummies.find().count())  //--->Line2
        });
    });
});

Template.dummies.helpers({
    dummies: function(){
        return Dummies.find();
    }
});

Both Line1 and Line2 are being executed just once. Shouldn't they be executed everytime Dummies.insert() is called?

I mean, shouldn't they be called whenever template is updated?

If I have misunderstood the docs, Is there a way to achieve this?

Upvotes: 0

Views: 2168

Answers (1)

Jos Harink
Jos Harink

Reputation: 358

The code you show looks good. And yes, the code inside autorun is rerun each time a reactive source is changed. Because the Dummies collection is a reactive source this should trigger a rerun on each insert in the collection.

I copied your code into a small project and it works as expected. Every 2 seconds, a new record with incremented count is created and both Line 1 and Line 2 are show in the console. And the new count is displayed in in the template.

Can you show how you have setup your publish and subscribe? Or are you using autopublish?

Upvotes: 1

Related Questions