How to set Meteor variables in template javascript tags


#1

I have the below code where ‘Message B’ outputs before ‘Message A’.
Is this correct operation? I thought that functions in onCreated got
executed first before helpers but that doesn’t seem to be the case. As a
result the variable x in the template, which is obtained from mongodb,
sometimes does and sometimes doesn’t have a value.

I also tried using Meteor.apply but that gave the same inconsistent results.

What am I doing wrong ?

Template.homepage.onCreated( function() {
    Meteor.call('getvalueofX', function(err,result){
        if(!err) {
              //Message A
             console.log("Message A: setting session variable x = " + result);
             Session.set("x",result);
        } 
    }
  });

Template.homepage.helpers({ 
    x: function() {
           // Message B
           console.log("Message B: getting session variable x = " + Session.get("x"));
           return Session.get("x");
    },

 });

<template name="homepage">
<script type="text/javascript">
 var x = '{{x}}';
  // the javascript variable is often undefined here 
  // which causes the app to break
</template>

I tried using Meteor.apply shown below instead but I get the same error:

// still doesn't work
 Meteor.apply('getvalueofX',[],true,function(err,result) { 
            if(!err) Session.set("x",result);
   } );

#2

Please try ReactiveMethode.


#3

Thanks for the tip but I’m not sure I understand. The Meteor.calls are not returning in time for the variables to get set. So method calls fail due to variables being undefined . And these variables are being set by async Meteor.calls.

Please let me know what I am missing.


#4

As you say yourself, the Meteor.call() is asynchronous. That means that that the Template.homepage object can be created before the method returns data to the call.

In turn, that means that the helper can be invoked before the method returns.

If you cannot use a Meteor pub/sub (which allows you to confirm your data is ready) - as I think @theara is suggesting, then you need to amend your code to allow for the eventuality that your Session.get() can be invoked before your Session.set() - perhaps do a Session.set(null) at the top of your onCreated (before the call) and test for this in your helper, or use a separate reactive variable as a semaphore.