简体   繁体   中英

Handlebar Registerhelper in a loop not working in Meteor

I'm trying to make a dynamic set of handlebar helpers in an array, but it isn't working. Here's my code. Client JS

Meteor.startup(function(){
  Meteor.call('getTabs', function(e, r){//This works and returns the array it should
  //At the moment, r returns ["Home", "Dorem"]

  Session.set('tabs', r); //Again, this part works

  for(i in r){
    var bn = r[i] + 'bool'; //The name of the session.get for each thing, e.g. 'Homebool'
    Session.set(bn, false);//Makes them all false
    Handlebars.registerHelper(bn + 'e',function(){//Different name for clarification purposes, e.g. 'Homeboole'
      return Session.get(bn); //Should return
    });

  }
  switchTabs('Home');

  Session.set('Homebool', true);//Makes Homebool true so it'll display automatically


});

  function switchTabs(templateName){
    var t = Session.get('tabs');
    for(i in t)
    {
      console.log(t[i] + ":" + templateName);
      console.log(t[i] + ":" + (t[i] == templateName) + " switch")
      if(t[i] == templateName)
        Session.set(t[i] + 'bool', true);
      else
        Session.set(t[i] + 'bool', false);
    }
  }


  Template.navbar.events({
      'click .tabSwitch' : function(e, t){
        console.log(e.currentTarget.id + "Current");
        switchTabs(e.currentTarget.id);
      }
  });
  Template.navbar.show = function(){//This makes a navigation bar with

    var ret = "<div class='pure-menu pure-menu-open pure-menu-horizontal'><a href='#' class='pure-menu-heading'>Hello World</a><ul>";
    var t = Session.get('tabs');
    for(i in t){
      ret+="<li id='aa'><a href='#' class='tabSwitch' id='" + t[i] + "'>" + t[i] + "</a></li>";
    }
    ret+="</ul></div>";
    console.log(ret);
    return ret;
  }

HTML

<body>
{{> navbar}}
{{#if Homeboole}}
  {{> Home}}
{{/if}}

{{#if Doremboole}}
  {{> Dorem}}
{{/if}}

</body>

<template name="Home">
<p>Home</p>
</template>

<template name="Dorem">
<p>Dorem</p>
</template>

<template name="navbar">
{{{show}}}
</template>

What should happen is that the content switches when you click the 'Home' or 'Dorem' tags. However, it only switches when clicking the 'Dorem' element and, when it does switch, it displays the things from the 'Home' and 'Dorem' template. Does anybody have a solution? Thanks.

I figured it out. I had to go for a bit of a different approach. Rather than make a bunch of new Handlebar handlers, I just made one which takes an arg.

      Handlebars.registerHelper('test', function(a){
       return Session.get(a + 'bool');
      });

Then, in the HTML, I would use it like so.

{{#if test "Home"}}
  {{> Home}}
{{/if}}

{{#if test "Dorem"}}
  {{> Dorem}}
{{/if}}

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