javascript - Materialize: dropdown in "if" statement doesn't work -


i tried implement dropdown list visible when user signed in. dropdown list works when outside "if" statement not inside. buttons "foo" , dropdown button shown, doesn't "dropdown".

header.html

<!-- header --> <template name="header"> <nav>     <div class="nav-wrapper">         <a  class="brand-logo" href="{{pathfor 'home'}}">logo</a>         <ul id="nav-mobile" class="right hide-on-med-and-down">             {{#if currentuser}}                 <!-- dropdown1 trigger -->                 <li>                     <a class="dropdown-button" href="#!" data-activates="dropdown1">                         <i class="mdi-navigation-more-vert"></i>                     </a>                 </li>                  <li><a href="#">foo</a></li>             {{else}}                 <li><a href="{{pathfor 'signin'}}">sign in</a></li>             {{/if}}              <li><a href="{{pathfor 'about'}}">about</a></li>         </ul>     </div> </nav>  <!-- dropdown1 structure --> <ul id="dropdown1" class="dropdown-content">     <li class="signout"><a href="#!">sign out</a></li> </ul> </template> 

header.js

template.header.rendered = function () {     $(".dropdown-button").dropdown({         beloworigin: true // displays dropdown below button     }); }; 

what problem?

when template.header.onrendered lifecycle event first fired, dropdown html elements not yet inserted dom because condition {{#if currentuser}} not yet met (it takes small amount of time before being logged in meteor app, that's why meteor.user being reactive handy !).

this why jquery dropdown initialization fails : dom not yet ready ! solution quite simple thoug : refactor spacebars code put dropdown markup in 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 child template inside header template :

{{#if currentuser}}   {{> dropdown}} {{else}}   {{! ... }} {{/if}} 

this way dropdown have own onrendered lifecycle event triggered after user logged in, , @ time dropdown dom ready.

template.dropdown.onrendered(function(){   this.$(".dropdown-button").dropdown({     beloworigin: true // displays dropdown below button   }); }); 

sometimes refactoring code smaller subtasks not matter of style, makes things work way intended.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -