How to pass the data to a template using blaze-layout render? - meteor

I tried the following code to pass data to a template and receive it in onCreated() but I cannot access the data.
deviceInfo.js:
BlazeLayout.render('layout',{main:'deviceInfo',stats:'paramstats',attr:"SOME_DATA"});
deviceInfo.html:
{{>Template.dynamic template=stats data=attr}}
paramstats.js:
Template.paramstats.onCreated( () => {
console.log("onCreated");
console.log("Data is:",this.data.attr);
});
But I get TypeError: Cannot read property 'attr' of undefined.
where am I going wrong?

You need to use the normal function syntax for onCreated callback. Arrow function will bind the context of your function to the outer scope automatically, it is the cause of your problem. Try this:
Template.paramstats.onCreated(function() {
console.log("onCreated");
console.log("Data is:",this.data.attr);
});

I am using Meteor 1.4.# and I was able to retrieve the parameters like so:
BlazeLayout.render("page", {
params: ['fullscreen', 'route']
});
// page.js
Template.page.onCreated(function() {
let params = this.data.params();
console.log(params);
}

Not quite sure why you're using two levels of indirection. BlazeLayout.render() is giving you one level and then you're using a dynamic template within that? Why not directly render the template you ultimately want using BlazeLayout.render()?
In any case, you're dereferencing your data context indirectly.
In the BlazeLayout.render() call you're setting the attr variable to some value.
Then in your dynamic template you're using data=attr but this means that inside your template helpers that this is going be have the value of attr. There will be no data subkey added automatically.
You don't show the value that you're setting for attr so it's not even clear that you have an attr subkey in your attr variable, that would also be confusing to anyone else who ever tries to debug your code.
#khang is correct about not using the arrow function syntax in onCreated(), try:
Template.paramstats.onCreated(function(){
console.log("onCreated");
console.log("Data is:",this);
});
this should have whatever value you stuffed into attr in your BlazeLayout.render()

Related

Send Object from one template to another via iron router, meteor

I am getting some data on a template via meteor.call. Now I want to send the object to another template. I am using iron:router for routing. Below is my code :
Meteor.call(functionName, function(err, res){
if(!err){
//do something
Router.go('templateName', {
data : res
});
}
});
Router.route('/url/:data?', function(){
console.log(this.params.data);
})
In the console.log, I am getting the object as string. Data returned is
"object Object" => (this is a string, not an object)
I don't want to use Session variables as they are global. I am confused as to how to send data from one template to another.
The templates are not related to each other (parent-child relation) and hence I can't use {{>templateName data=this}}
I also tried using query parameters as suggested by #Jankapunkt
Router.go('templateName', {},{
query : res
});
Router.route('/url/:data?', function(){
console.log(JSON.stringify(this.params.query));
});
Printed statement :
{"0":"[object Object]","1":"[object Object]","2":"[object Object]","3":"[object Object]","4":"[object Object]","5":"[object Object]","6":"[object Object]","7":"[object Object]","8":"[object Object]","9":"[object Object]","10":"[object Object]","11":"[object Object]","12":"[object Object]","13":"[object Object]","14":"[object Object]"}
Any idea on how to proceed?

Returned value from Meteor Helper not showing up in template

I have a Meteor Helper that does a GET request and am supposed to get response back and pass it back to the Template, but its now showing up the front end. When I log it to console, it shows the value corerctly, for the life of mine I can't get this to output to the actual template.
Here is my helper:
UI.registerHelper('getDistance', function(formatted_address) {
HTTP.call( 'GET', 'https://maps.googleapis.com/maps/api/distancematrix/json? units=imperial&origins=Washington,DC&destinations='+formatted_address+'&key=MYKEY', {}, function( error, response ) {
if ( error ) {
console.log( error );
} else {
var distanceMiles = response.data.rows[0].elements[0].distance.text;
console.log(response.data.rows[0].elements[0].distance.text);
return distanceMiles;
}
});
});
In my template I pass have the following:
{{getDistance formatted_address}}
Again, this works fine and shows exactly what I need in the console, but not in the template.
Any ideas what I'm doing wrong?
I posted an article on TMC recently that you may find useful for such a pattern. In that article the problem involves executing an expensive function for each item in a list. As others have pointed out, doing asynchronous calls in a helper is not good practice.
In your case, make a local collection called Distances. If you wish, you can use your document _id to align it with your collection.
const Distances = new Mongo.collection(); // only declare this on the client
Then setup a function that either lazily computes the distance or returns it immediately if it's already been computed:
function lazyDistance(formatted_address){
let doc = Distances.findOne({ formatted_address: formatted_address });
if ( doc ){
return doc.distanceMiles;
} else {
let url = 'https://maps.googleapis.com/maps/api/distancematrix/json';
url += '?units=imperial&origins=Washington,DC&key=MYKEY&destinations=';
url += formatted_address;
HTTP.call('GET',url,{},(error,response )=>{
if ( error ) {
console.log( error );
} else {
Distances.insert({
formatted_address: formatted_address,
distanceMiles: response.data.rows[0].elements[0].distance.text
});
}
});
}
});
Now you can have a helper that just returns a cached value from that local collection:
UI.registerHelper('getDistance',formatted_address=>{
return lazyDistance(formatted_address);
});
You could also do this based on an _id instead of an address string of course. There's a tacit assumption above that formatted_address is unique.
It's Meteor's reactivity that really makes this work. The first time the helper is called the distance will be null but as it gets computed asynchronously the helper will automagically update the value.
best practice is not to do an async call in a helper. think of the #each and the helper as a way for the view to simply show the results of a prior calculation, not to get started on doing the calculation. remember that a helper might be called multiple times for a single item.
instead, in the onCreated() of your template, start the work of getting the data you need and doing your calculations. store those results in a reactive var, or reactive array. then your helper should do nothing more than look up the previously calculated results. further, should that helper be called more times than you expect, you don't have to worry about all those additional async calls being made.
The result does not show up because HTTP.call is an async function.
Use a reactiveVar in your case.
Depending on how is the formated_address param updated you can trigger the getDistance with a tracker autorun.
Regs
Yann

Meteor: How to access Template's Instance key in Blaze directly (without helper)?

Template.Demo.onCreated(function() {
this.test = 'Text';
});
How to access that template's instance test key in Blaze directly (without creating a helper function)?
{{Template.instance.test}} seems not to work (it was suggested here).
I don't believe this is possible with current versions of Blaze. That being said, you can simulate this by declaring a single global Template helper function, like:
Template.registerHelper('instance', function () {
return Template.instance();
});
Just define this once in a common client location, and you can then reference instance in any of your Template's. So you could reference your test variable like:
{{instance.test}}

Cannot read property of undefined, but property exists

I am getting a curious error in a template helper and I was hoping someone could lay eyes on it with me. Basically the error I'm getting in the console of the client is that the getArena().height is undefined. However, console.log(getArena().height) returns the correct property value. It appears to be a timing issue causing me to get the error, but my application is actually working. What can I do to alleviate this console error?
//My template helper function
yGrids: function() {
console.log(getArena);
console.log(getArena().height);
var yArray = [];
for (var i=0;i<(getArena().height);i++){
yArray.push({});
}
return yArray;
},
// The console results
function getArena() { // 50
return Arenas.findOne(Session.get('arena_id')); …
Exception in template helper: TypeError: Cannot read property 'height' of undefined
at Object.yGrids (http://localhost:3000/app/app.js?hash=c17abf51d6af6541e868fa3fd0b26e34eea2df28:94:35)
at http://localhost:3000/packages/blaze.js?hash=ef41aed769a8945fc99ac4954e8c9ec157a88cea:2994:16
at http://localhost:3000/packages/blaze.js?hash=ef41aed769a8945fc99ac4954e8c9ec157a88cea:1653:16
at http://localhost:3000/packages/blaze.js?hash=ef41aed769a8945fc99ac4954e8c9ec157a88cea:3046:66
at Function.Template._withTemplateInstanceFunc (http://localhost:3000/packages/blaze.js?hash=ef41aed769a8945fc99ac4954e8c9ec157a88cea:3687:12)
at http://localhost:3000/packages/blaze.js?hash=ef41aed769a8945fc99ac4954e8c9ec157a88cea:3045:27
at Object.Spacebars.call (http://localhost:3000/packages/spacebars.js?hash=65db8b6a8e3fca189b416de702967b1cb83d57d5:172:18)
at http://localhost:3000/app/app.js?hash=c17abf51d6af6541e868fa3fd0b26e34eea2df28:24:22
at .<anonymous> (http://localhost:3000/packages/blaze.js?hash=ef41aed769a8945fc99ac4954e8c9ec157a88cea:2754:17)
at http://localhost:3000/packages/blaze.js?hash=ef41aed769a8945fc99ac4954e8c9ec157a88cea:1875:20
function getArena() { // 50
return Arenas.findOne(Session.get('arena_id')); …
2
This is a very common issue in Meteor helpers when referring to a collection which may not yet have been loaded via a subscription. In general you want to show a loading template instead of your actual layout until your subscription is ready. Or (less elegant) you can defend yourself with:
var arena = getArena();
var height = arena && arena.height;
Whatever getArena() returns you ought to store it in the reactive variable by setting the reactive variable and you can access the reactive var in helper by get() method

Why Does Firebase orderByChild() return undefined?

I've got a Firebase with a simple bit of data:
There's a list of "players", each with a self-generated GUID, and each containing a value "Count". At my request (e.g. using once()), I want to be able to query the players sorted by the Count value. So, based on the Firebase documentation, I'm using orderByChild(), but it always comes up as undefined when I run the code:
var fb = new Firebase("https://morewhitepixels.firebaseio.com/");
fb.child("players").orderByChild("Count").once("value",function(data) {
// do something with data
});
But this code always returns Uncaught TypeError: undefined is not a function pointing to that second line of code.
What am I missing?
I'm not sure what you do inside the callback, but this works fine:
fb.child("players").orderByChild("Count").once("value",function(data) {
console.log(data.val());
});
Keep in mind that the data parameter is not the actual data yet. It's a DataSnapshot on which you have to call val() first.
You'll probably want to loop through the children, which you can do like this:
fb.child("players").orderByChild("Count").once("value",function(data) {
data.forEach(function(snapshot) {
console.log(snapshot.val().Count);
});
});
The above example prints out all your children in the order you requested:
120320
181425
185227
202488
202488
202488
202488
245197
245197
487320
Alternatively you can use on('child_added' instead:
fb.child("players").orderByChild("Count").on("child_added",function(snapshot) {
console.log(snapshot.val().Count);
});

Resources