tidee
April 26, 2015, 11:54pm
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);
});
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
tidee
April 28, 2015, 11:17pm
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?
You can waitOn
the Boxes subscription so that your template does not render before it’s ready.
tidee
April 29, 2015, 8:13am
5
I a already doing this in the router.js file, but the template still appears briefly before the logic licks in.
Steve
April 29, 2015, 12:44pm
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>
1 Like