How to auto run a function when data changes

I want to automatically run a function when the number of records in a collection changes. What is the way to do this?
So far I have tried:

toggleMsg = function (num) {
    if ( num > 0 ){
        $(".msg").addClass("hidden");
    }
    else{
        $(".msg").removeClass("hidden");
    }
};


Tracker.autorun(function () {
    var num = Boxes.find().count();
    toggleMsg(num);
});

Tried this?

Template.foo.helpers({
    msgVisibility: function () {
        if (Boxes.find().count() > 0) {
            return "hidden";
        } else {
            return "";
        }
    }
});

<template name="foo">
    <div class="msg {{msgVisibility}}">
        blabla...
    </div>
</template>
1 Like

Great … now what if I wanted the msg to be hidden from the start when the page loads - at present this template appears briefly before the logic kicks in?

You can waitOn the Boxes subscription so that your template does not render before it’s ready.

I a already doing this in the router.js file, but the template still appears briefly before the logic licks in.

Don’t manage subscriptions in the router. Prefer something like this:

Template.foo.created = function() {
  this.subscribe('boxes');
}

Template.foo.helpers({
    msgVisibility: function () {
        if (!Template.instance().subscriptionsReady() || Boxes.find().count() > 0) {
            return "hidden";
        } else {
            return "";
        }
    }
});

<template name="foo">
    <div class="msg {{msgVisibility}}">
        blabla...
    </div>
</template>
1 Like