在活动链路的路由更改中重新运行辅助功能

And*_*oss 3 meteor iron-router

我一直在使用Meteor + Iron Router来处理我正在研究的多页面应用程序,而且我已经陷入了关于命名率的辅助函数.具体来说,我一直试图让我的导航栏选项卡的活动类更新每个路由更改.

以下是我项目的相关代码:

router.js

Router.configure({
  layoutTemplate: 'mothership',
  yieldTemplates: {
  'header' : {to: 'header'},
  'footer': {to: 'footer'}
  },
});

Router.map(function () {
  // Home page
  this.route('home', {
    path: '/',
    template: 'home',
  });

  this.route('about', {
    path: '/about',
    template: 'about',
  });

  this.route('emails', {
    path: '/emails',
    template: 'emails',
  });

  this.route('people', {
    path: '/people',
    template: 'people',
  });
}); 
Run Code Online (Sandbox Code Playgroud)

mothership.html

<template name="mothership">
  <a href="#content" class="sr-only">Skip to content</a>
  <div id="wrap">
    <!-- header -->
    <div>{{yield 'header'}}</div>
    <div id="content">{{yield}}</div>
  </div>

  <div id="push"></div>
  <div id="footer">
    {{yield 'footer'}}
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)

了header.html

...bootstrap stuff...
<a class="navbar-brand" href="{{pathFor 'home'}}">Mailchacho</a>
<li class="{{activeRoute 'about'}}"><a href="{{pathFor 'about'}}">About</a></li>
<li class="{{activeRoute 'emails'}}"><a href="{{pathFor 'emails'}}">Sent Emails</a></li>
<li class="{{activeRoute 'people'}}"><a href="{{pathFor 'people'}}">People</a></li>
...bootstrap stuff...
Run Code Online (Sandbox Code Playgroud)

header.js

Handlebars.registerHelper('activeRoute', function(name) {
  var active = location.pathname === Router.path(name);
  return (active) ? 'active' : '';
});

// I know I can use Template.headers.helpers... to do this as well, I just found the registerHelper to be cleaner.
Run Code Online (Sandbox Code Playgroud)

当我从头开始加载页面时,会分配正确的活动类,但是当在页面上更改路由时,活动类不会更新.使用断点,我可以看到在更改时不调用'activeRoute'函数.

有趣的是,如果我向router.js添加数据字典,它更新.我的猜测是数据字典表明路由之间发生了某些变化,迫使刷新.我想做的是在不需要传递数据字典的情况下进行刷新.

由于Iron Router仍然相当新,我无法在网上找到太多东西.我发现最接近的是github上的这个问题(https://github.com/EventedMind/iron-router/issues/103),但最后的评论从未得到解决,这似乎与我的相似.

考虑到上述情况,有没有什么方法可以指示辅助函数在路由更改时重新运行而不传递虚拟数据字典?我觉得可能需要像Deps.autorun这样的东西,但这感觉不对.我仍然是Meteor&Iron路由器的新手,所以任何帮助都会受到赞赏.谢谢!

Ser*_*soy 6

你的是一个常见的问题,因此Mike Fitzgerald为此目的建立了一个包:

https://atmosphere.meteor.com/package/iron-router-active

给出的例子如下:

<nav>
    <ul>
        <li class="{{ isActive 'dashboard' }}">...</li>
        <li class="{{ isActive 'dashboard|root' }}">...</li>
        <li class="{{ isActive 'users' 'on' }}">...</li>
        <li class="{{ isActivePath 'products' }}">...</li>
    </ul>
</nav>
Run Code Online (Sandbox Code Playgroud)

和d通过车把助手这是所谓的工作isActive,isActivePath,isNotActiveisNotActivePath.