简体   繁体   中英

Meteor Force Rerender of Handlebar Helpers

In Meteor, I have a navigation bar with a custom handlebar method that determines whether or not the tab is active.

JS:

Handlebars.registerHelper('getClass',function(a){
    url = document.URL.split("/"); //e.g. http://test.com/something, so 3rd value will have link thing
    url = "/" + url[3];
    val = Router.path(a);
    return url == val ? "active" : "";
});

HTML Snippet:

  <li class="{{getClass 'homepage'}}"><a href="{{pathFor 'homepage'}}">Home</a></li>
  <li class="{{getClass 'content'}}"><a href="{{pathFor 'content'}}">Content</a></li>
  <li class="{{getClass 'items'}}"><a href="{{pathFor 'items'}}">Items</a></li>

This sets the appropriate active class on a nav-block if I open an entirely new tab, navigating to something like http://localhost:3000/content . However, it won't update the active class if I merely click a new tab. For instance, from the home page to the content page. However, if I click the items tab and then click another tab, it will update, but just once. So if I go to the items tab, items will have the active class and the next class I click will then get it, removing it from items . This only works once, unfortunately. I think it is because items has content from a DB, but I'm not sure. Anyways, I need a way to rerender handlebar helpers, if this is at all possible.

I've tried using the following JS to no avail:

Content = {};
Content._dep = new Deps.Dependency;

Template.header.events({
  'click a': function () {
      console.log('abc');
    Content._dep.changed();
  }  
})

Does anybody have a way to rerender the handlebars without having to physically reload the page?

Thanks.

I just fixed it. Basically, I added a session with a random number, and updated that on click. It seemed to have done the trick.

Updated code:

Handlebars.registerHelper('getClass',function(a){
    url = document.URL.split("/"); //e.g. http://test.com/something, so 3rd value will have link thing
    url = "/" + url[3];
    val = Router.path(a);
    if(Session.get('r'))
        void(0);
    return url == val ? "active" : "";
});


Template.header.events({
  'click a': function () {
      Session.set('r', Math.random() + "");
  }  
})

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