How to auto run a function when data changes


#1

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);
});

#2

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>

#3

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?


#4

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


#5

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


#6

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>