not able to display the aggregation values in meteor template - meteor

I am able to get the aggreate values from server to client, but could not display it on the template. Am i missing something here.Appreciate your help.Iam a newbie in meteor.
//client side javascript
Template.DashboardCategoriesChart.helpers({
'CategoryAggregateItem':function(){
var res;
Meteor.call("getAggregateCategoriesSum",function(errors,results){
console.log("results value: "+ JSON.stringify(results))
return results ;
};
};
});
//stringfy value returned
results value: [
{"_id":"Household","totalAmount":420},
{"_id":"Insurance","totalAmount":235},
{"_id":"Family","totalAmount":1358},
{"_id":"Utilities","totalAmount":5371.5},
{"_id":"Automobile","totalAmount":500},
{"_id":"Home Office","totalAmount":290},
{"_id":"Travel","totalAmount":14},
{"_id":"Food","totalAmount":303}
]
//Template
{{#each CategoryAggregateItem}}
<tr>
<td>{{_id}}</td><td>{{totalAmount}}</td>
</tr>
{{/each}}

The following code worked, thanks a ton JeremyK for leading to right direction.
Template.DashboardCategoriesChart.helpers({
'CategoryAggregateItem':function(){
return Template.instance().CategoryAggregateItem.get(); //this.CategoryAggregateItem;
}
});
Template.DashboardCategoriesChart.onCreated(function () {
var instance = this;
this.CategoryAggregateItem = new ReactiveVar(null);
Meteor.call("getAggregateCategoriesSum",function(errors,results){
console.log("results value: "+ JSON.stringify(results))
instance.CategoryAggregateItem.set(results);
})
})

Try changing your client side javascript to this:
Template.DashboardCategoriesChart.onCreated(function () {
_this = this;
_this.CategoryAggregateItem = new ReactiveVar(null);
Meteor.call("getAggregateCategoriesSum",function(errors,results){
console.log("results value: "+ JSON.stringify(results))
_this.CategoryAggregateItem.set(results);
}
});
Template.DashboardCategoriesChart.helpers({
'CategoryAggregateItem':function(){
return Template.instance().CategoryAggregateItem.get();
});
When the Callback from Meteor.Call is triggered, it will update the ReactiveVar. This causes the template to rerender and display the retrieved data.
You may also want to provide alternative markup in your template for when the helper returns null, before the data is received by the client.

Related

Meteor - publish and subscribe issue

I am new to Meteor and trying to get publish and subscribe to work. Here is my code for subscribe:
//isClient
Session.set("userSetLimit",10);
Template.MoodList.helpers({
hlpinvoices: function(){
var curinvoices = Meteor.subscribe('invoices', Meteor.userId(),Session.get("userSetLimit"));
return curinvoices;
}
});
publish:
//isServer
Meteor.publish('invoices',function (creator,limit) {
return Invoices.find({CreatedBy:creator},{sort:{DateCreated:-1}, limit:limit});
})
and template:
<template name="MoodList">
<ul>
{{#each hlpinvoices}}
{{> invoice}}
{{/each}}
</ul>
</template>
And this is the error I got:
Exception in defer callback: Error: {{#each}} currently only accepts
arrays, cursors or falsey values.
But if I use do:
//isClient
Session.set("userSetLimit",10);
Template.MoodList.helpers({
hlpinvoices: function(){
return Invoices.find({CreatedBy:Meteor.userId()},{sort:{DateCreated:-1}, limit:Session.get("userSetLimit")});
}
});
I don't have problem. Any idea how to resolve this?
subscribe is something you call in order to get data from your server, it doesn't actually return any data itself - hence the error. You'll want to call subscribe in the onCreated method of your template:
Template.MoodList.onCreated( function() {
Meteor.subscribe('invoices', Meteor.userId(),Session.get("userSetLimit"));
});
Then in your helper you can return the invoices:
Template.MoodList.helpers({
hlpinvoices: function(){
return Invoices.find({CreatedBy:Meteor.userId()},{sort:{DateCreated:-1}, limit:Session.get("userSetLimit")});
}
});
You can learn more about subscribing to data in the Meteor Guide. Hope that helps!
Meteor.subscribe gives you subscription Id only .Try this
Template.MoodList.helpers({
hlpinvoices: function(){
Meteor.subscribe('invoices', Meteor.userId(),Session.get("userSetLimit"));
var curunnvoices=Invoices.find({CreatedBy:Meteor.userId()},{sort:{DateCreated:-1}, limit:Session.get("userSetLimit")})
return curinvoices;
}
});

How can I be updated of an attribute change in Meteor?

I have a template that subscribes to a document. Everything works fine in the DOM and Blaze updates as soon as an attribute used in the template helpers is changed.
I also have some custom logic that doesn't appears in the DOM and depends on the document attributes. How can I call a function to change that logic when an attribute is updated?
I'm looking for something like this.data.attr.onChanged where this would refer to the template and this.data is the data send to the template, as usual; or a Meteor function that is rerun on change where I could put my callback in.
I hoped that template.onRendered would be recalled, but that's not the case.
I've read a lot about reactive variables, but could not find how they could be useful here.
[edit] the change is coming from the server that is communicating with another service
I've tried Tracker.autorun like this:
Template.editItem.onRendered(function() {
var self = this;
Tracker.autorun(function () {
console.log("tracker", self.data.item.socketId);
});
});
And the corresponding route is:
Router.route('editItem', {
path: '/edit/:_id',
waitOn: function () {
var sub = Meteor.subscribe('item', this.params._id);
return [sub];
},
data: function () {
return {item: Items.findOne(this.params._id)};
},
action: function () {
if (this.ready())
this.render();
}
});
At some point, the property socketId gets removed from the corresponding document by the server and I'm sure of that since I've checked in the shell, but the tracker doesn't rerun.
Use Template.currentData().item.socketId instead of self.data.item.socketId, this will give you reactivity.
And in templates generally, use self.autorun instead of Tracker.autorun (unlike Tracker.autorun, this will ensure that the autorun is stopped when the template is destroyed). Likewise, if you want to subscribe in a template, use self.subscribe instead of Meteor.subscribe.
Code to see if Template.currentData() works for you:
Template.editItem.onRendered(function() {
var self = this;
self.autorun(function () {
console.log("tracker", Template.currentData().item.socketId);
});
});
I'm not sure if I got you right, you just want to observe your html inputs and apply the new value to your helper method(s) on change?!
If so, you could use session variables to store your temporary UI state:
// observe your input
Template.yourTemplate.events({
"change #inputA": function (event) {
if(event.target.value != "") {
Session.set("valueA", event.target.value);
}
}
}
// apply the changed value on your helper function
Template.yourTemplate.helpers({
getSomeData: function() {
var a = Session.get("valueA");
// do something with a ..
}
}
In meteor's official todo app tutorial this concept is also used.
If you need to re-run something which is not part of DOM/helper, you can use Tracker.autorun. According to meteor docs, Run a function now and rerun it later whenever its dependencies change.
here's the docs link
Try moving the subscription into Tracker.autorun
Template.editItem.onRendered(function() {
var self = this;
Tracker.autorun(function () {
Meteor.subscribe('item', this.params._id);
console.log("tracker", self.data.item.socketId);
});
});
Of course you can't use this.params there so you can store this as a Session variable

this.findAll not working on sub-template

When I try to use this.findAll on a template where the selector is in a sub-template, findAll returns nothing.
Here's the HTML:
<template name="products">
{{#each productList}}
{{> product }}
{{/each}}
</template>
<template name="product">
<div class="box">{{name}}</div>
</template>
Here's the JS:
Template.products.helpers({
productList: function() {
var all = Products.find({}).fetch();
return all;
}
});
Template.products.rendered = function(){
var boxes = this.findAll('.box');
console.log(boxes.length);
}
Output of boxes.length is 0. Any ideas how I could get the "box" elements?
According to the docs for findAll:
Only elements inside the template and its sub-templates can match parts of the selector.
So it should work for sub-templates. I tried this with a fixed array of products and it worked, which implies that you are just seeing a delay between the call to rendered and the products being fetched. For example if you do:
Template.products.events({
'click .box': function (e, t) {
var boxes = t.findAll('.box');
console.log(boxes.length);
}
});
Then if you click on one of the boxes, you should see the correct number logged to the console. In short, I think the test may just be invalid. If you are using iron-router, you could try adding a waitOn for the products - that may ensure they arrive before the rendered call.
Here's what I did to run a script after all products have been loaded.
I've added last_product property in all the products.
Template.products.helpers({
productList: function() {
var all = Products.find({}).fetch();
var total = all.length;
var ctr = 0;
all.forEach(function(doc){
doc.last_product = false;
ctr++;
if(ctr == total)
{
doc.last_product = true;
}
return doc;
});
return all;
}
});
Then instead of "Template.products", I used "Template.product" to detect if the last product is rendered. When the last product is rendered, run the script.
Template.product.rendered = function(){
if(this.data.last_product){
var boxes = $('.pbox');
console.log(boxes.length);
}
}
boxes.length now has the correct length.
Thanks to David for the idea!
Here's the correct answer. I've added this to my iron-router route:
action : function () {
if (this.ready()) {
this.render();
}
}
Found the answer from https://stackoverflow.com/a/23576039/130237 while I was trying to solve a different problem.

meteor and textareas

Ok so I'm not sure why I can't render the code. First if I console.log users.content I get the content I want but I'm some how not able to pass it to a textarea so that it show's it...
Users = new Meteor.Collection("users");
if(Meteor.is_client){
Template.inputUser.code = function(){
var el = Users.find({name:"oscar"});
el.forEach(function(users){
console.log(users.content);
})
}
}
And then on my html template I have
<body>{{> inputUser}}</body>
<template name="inputUser">
<textarea>{{content}}</textarea>
</template>
And I would have a record on the db suck as so
if(Meteor.is_server)
Users.insert({name:"oscar",content:"hello world"})
Thanks for your help guys.
Firstly your method Template.inputUser.code should return something, you should also note that it wouldn't be called with that template either as it needs a {{code}} call in it rather than {{content}}
The second point is database contents are not always available if you have disabled the autopublish package, if so check out using publish(in the server code) and subscribe(in the client code): http://docs.meteor.com/#meteor_subscribe you can use this to check when the client has all the data to display. Something like:
Meteor.subscribe('allusers', function() {
Template.inputUser.code = function(){
var user = Users.findOne({name:"oscar"});
return user.content;
}
});
...
Meteor.publish('allusers', function() {
return Users.find();
});

dynamically inserting templates in meteor

Ok so I've got my template in its own file named myApp.html. My template code is as follows
<template name="initialInsertion">
<div class="greeting">Hello there, {{first}} {{last}}!</div>
</template>
Now I want to insert this template into the DOM upon clicking a button. I've got my button rendered in the DOM and I have a click event tied to it as follows
Template.chooseWhatToDo.events = {
'click .zaButton':function(){
Meteor.ui.render(function () {
$("body").append(Template.initialInsertion({first: "Alyssa", last: "Hacker"}));
})
}
}
Now obviously the $("body").append part is wrong but returning Template.initialInsertion... doesn't insert that template into the DOM. I've tried putting a partia {{> initialInsertion}}but that just errors out because I dont have first and last set yet... any clues?
Thanks guys
In meteor 1.x
'click .zaButton':function(){
Blaze.renderWithData(Template.someTemplate, {my: "data"}, $("#parrent-node")[0])
}
In meteor 0.8.3
'click .zaButton':function(){
var t = UI.renderWithData(Template.someTemplate, {my: "data"})
UI.insert(t, $(".some-parrent-to-append"))
}
Is first and last going into a Meteor.Collection eventually?
If not, the simplest way I know is to put the data into the session:
Template.chooseWhatToDo.events = {
'click .zaButton' : function () {
Session.set('first', 'Alyssa');
Session.set('last', 'Hacker');
}
}
Then you would define:
Template.initialInsertion.first = function () {
return Session.get('first');
}
Template.initialInsertion.last = function () {
return Session.get('last');
}
Template.initialInsertion.has_name = function () {
return Template.initialInsertion.first() && Template.initialInsertion.last();
}
Finally, adjust your .html template like this:
<template name="initialInsertion">
{{#if has_name}}
<div class="greeting">Hello there, {{first}} {{last}}!</div>
{{/if}}
</template>
This is the exact opposite solution to your question, but it seems like the "Meteor way". (Basically, don't worry about manipulating the DOM yourself, just embrace the sessions, collections and template system.) BTW, I'm still new with Meteor, so if this is not the "Meteor way", someone please let me know :-)
I think you may want to use Meteor.render within your append statement. Also, note that if you are passing data into your Template, then you must wrap Template.initialInsertion in an anonymous function, since that's what Meteor.render expects. I'm doing something similar that seems to be working:
Template.chooseWhatToDo.events = {
'click .zaButton':function(){
$("body").append(Meteor.render(function() {
return Template.initialInsertion({first: "Alyssa", last: "Hacker"})
}));
}
}
Hope this helps!
Many answer here are going to have problems with the new Blaze engine. Here is a pattern that works in Meteor 0.8.0 with Blaze.
//HTML
<body>
{{>mainTemplate}}
</body>
//JS Client Initially
var current = Template.initialTemplate;
var currentDep = new Deps.Dependency;
Template.mainTemplate = function()
{
currentDep.depend();
return current;
};
function setTemplate( newTemplate )
{
current = newTemplate;
currentDep.changed();
};
//Later
setTemplate( Template.someOtherTemplate );
More info in this seccion of Meteor docs

Resources