简体   繁体   中英

Materialize: dropdown in “if” statement doesn't work

I tried to implement a dropdown list that is only visible when the user is signed in. The dropdown list works when outside the "if" statement but not inside. The buttons "Foo" and dropdown button are shown, however it 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 the button
    });
};

What could be the problem?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM