When your Template.header.onRendered
lifecycle event is first fired, the dropdown HTML elements are not yet inserted into the DOM because the condition {{#if currentUser}}
is not yet met (it takes a small amount of time before being actually logged in a Meteor app, that's why Meteor.user
being reactive is handy !).
This is why your jQuery dropdown initialization fails : the DOM is not yet ready ! The solution is quite simple thoug : refactor your Spacebars code to put the dropdown markup in its own separate template :
<template name="dropdown">
<li>
<a class="dropdown-button" href="#!" data-activates="dropdown1">
<i class="mdi-navigation-more-vert"></i>
</a>
</li>
<li><a href="#">Foo</a></li>
</template>
Then insert the child template inside your header template :
{{#if currentUser}}
{{> dropdown}}
{{else}}
{{! ... }}
{{/if}}
This way the dropdown will have its own onRendered
lifecycle event that will get triggered only after the user is logged in, and at this time the dropdown DOM will be ready.
Template.dropdown.onRendered(function(){
this.$(".dropdown-button").dropdown({
belowOrigin: true // Displays dropdown below the button
});
});
Sometimes refactoring your code into smaller subtasks is not just a matter of style, but it makes things work the way intended.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…