So, I’ve been banging my head all morning trying to figure this out and now it is time to get some help.
I am trying to create a chart using the chart.js package. Here is my code for my template.js in the client folder
Template.visualize.onRendered(function() {
var age = Questions.find({},{"age": "45-55"}).count();
alert(age); // returns 0 but there are values and should return a pos int
showAgeGroups();
});
// Following code block does not work.
Template.visualize.onCreated(function() {
var self = this;
self.subscribe("results");
});
function showAgeGroups() {
var data = [
{
//value: Questions.find({"age": "35-45"}).count(),
value : 3,
color: "green"
},
{
value: Questions.find({"age": "45-55"}).count(),
color: "red"
},
{
value: Questions.find({"age": "Over 55"}).count(),
color: "yellow"
}
];
var ctx = $("#age-groups").get(0).getContext("2d");
var ageChart = new Chart(ctx);
new Chart(ctx).Pie(data);
}
If I hard code the values like I did for the “35-45” age group, the chart shows up but shows 100% for 3 and nothing for anything else even though there are values there.
Thanks, eterps, but it did not work. I even tried the following
Template.visualize.onCreated(function() {
var subs = new SubsManager();
var self = this;
self.ready = new ReactiveVar();
self.autorun(function () {
var handle = subs.subscribe("results");
self.ready.set(handle.ready());
});
});
The onRendered method was not necessary(?) so I deleted it.
My new challenge is that even though the chart shows up properly, it is not reactive, i.e. will not update when new data is put into the database. Any suggestions?
The main concept with onCreated/onRendered is that you should wait for sub is ready and then do the render. So you can separate that logic into 2 steps:
@mrzfod Thanks! That really helps. The chart is still jittery on mouse over and shows incorrect data but not as schizophrenic as it was with my code.
It also redraws the entire chart when data is added to the collection.