Execute function in template after Meteor.user() loaded

Hey guys,
I’m very new on Meteor and having my first beginnerst question. I’m using ‘MaterializeCSS’ in my project. They hava own select fields which I have to initialize with “$(‘select’).material_select();”. I’m using it in my start.js:

Template.start.onRendered(function () {

$('select').material_select();
});

In my start.html, I have the current markup:

<select id="gender">
<option value="" selected disabled>Choose your gender</option>
<option value="1" {{selectedIf curUser.profile.gender 1}}>male
</option>
<option value="2" {{selectedIf curUser.profile.gender 2}}>female
</option>
</select>

selectedIf is a helper which return ‘selected’, curUser is a helper which returns “Meteor.user()”. Now, I’ve the following problem: The fields doesn’t get automatically selected, because when “onRendered” fires, the values for “curUser” aren’t available. This means that I’ve to set the values manually by jQuery, when curUser is available

My question is: How can I execute “$.select()” when Meteor.user() is available for this template?

Template.start.onRendered(function () {
  self = this;
  self.autorun(function() {
    if(Meteor.userId()) {
      self.$('select').material_select();
    } 
  });
});
1 Like

Hey,
thanks - it works :).

Might also be a good idea to stop the autorun after rendering the jquery component.

Only if itis not dependend on Meteor.user() data or similar. Lets imagine that the user logout and then login again with another profile.

Okay,
now I’m having a timing problem: My second select field doesn’t have the selected value on every load. If I add a timeout, f.e.:

window.setTimeout(function()
{
$('select').material_select();

$(".col > .caret").remove();
},500);

Is there any “professional” way to solve this issue - or do I have to remove the helpers and set my values in the Tracker and after setting them, I’ve to init $.material_select()?