简体   繁体   中英

Meteor show / hide element on button click

I have a template like so:

<template name="Menus">
  <button class="btn_create new_menu_toggle"><i class="fa fa-plus"></i> Create a new menu</button>
  <button class="btn_cancel new_menu_toggle"><i class="fa fa-times"></i> Cancel</button>
  {{> NewMenu}}
</template>

What I'm trying to accomplish is that initially only the btn_create is shown. If .btn_create is pressed, the {{> NewMenu}} is rendered and the .btn_create is replaced with btn_deny . Vice versa for the behaviour of btn_deny .

How would I go about doing this in Meteor I know I could probably accomplish this by adding / changing classes in vanilla Javascript, but I'd like to know if there's an easier method using Meteor / Blaze.

A simple pattern is to use a session variable to track the state

html:

<template name="Menus">
{{#if createMode}}
  <button class="btn_create new_menu_toggle"><i class="fa fa-plus"></i> Create a new menu</button>
  {{> NewMenu}}
{{else}}
  <button class="btn_cancel new_menu_toggle"><i class="fa fa-times"></i> Cancel</button>
{{/if}}
</template>

In your javascript you need to set up some event handlers to toggle the state:

Template.Menus.events({
  'click .btn_create'(ev){
    session.set('createMode',true);
  },
  'click .btn_cancel'(ev){
    session.set('createMode',false);
  }
});

When the template is rendered you need to initialize the session variable:

Template.Menus.onRendered(function(){
  session.set('createMode',true);
});

Finally you need the helper your template can use for the spacebars conditional expression:

Template.Menus.helpers({
  createMode(){
    return session.get('createMode');
  }
});

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