将"活动"类分配给EmberJS中的选定列表项

shs*_*shs 40 ember.js

我有一个列表,我想自动将一个项目设置为class ="active".给出以下引导代码:

<ul class="nav">
<li {{bindAttr class="atIndex:active"}}>{{#linkTo "index"}}Index{{/linkTo}}</li>
<li {{bindAttr class="atAbout:active"}}>{{#linkTo "about"}}About{{/linkTo}}</li>
<li {{bindAttr class="atLogin:active"}}>{{#linkTo "login"}}Login{{/linkTo}}</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

atIndex,atAbout和atLogin驻留在我的ApplicationController中.

渲染为:

<ul class="nav">
<li class="active"><a...>Index{{/linkTo}}</li>
<li><a...>About<a></li>
<li><a...>Login<a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

使用Ember 1.0 pre4做到这一点的最佳方法是什么?我宁愿不为每个视图或控制器添加特殊代码.

PS - atIndex: true有效,但atIndex: function() {return true; }.property().volatile()没有.这让我觉得我做错了什么.

谢谢!

les*_*syk 75

{{#link-to "dashboard" tagName="li" href=false}}
  <a {{bind-attr href="view.href"}}>
    Dashboard
  </a>
{{/link-to}}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个解决方法:只需重复内部链接,你就可以在li上使用活动类,并在锚点中使用href:{{#linkTo"dashboard"tagName ="li"href = false}} {{#linkTo "仪表板"}}仪表板{{/ linkTo}} {{/ linkTo}}我想最好的办法是编写自己的视图,但就我而言,这是一个纯粹的静态部分,不值得. (11认同)
  • 对于较新版本的Ember,请务必使用`link-to`而不是`linkTo`. (6认同)
  • 那个`view`变量来自哪里? (4认同)
  • 是的,如果你在链接中添加href = false,这实际上会生成有效的HTML.:-) (3认同)
  • 存在bind-attr`view.href`的文档在哪里?我似乎找不到它. (2认同)
  • 这有效,对我来说绝对没有意义.'active`类被适当添加,但我不知道为什么......使用ember 1.11.1 (2认同)

Mik*_*tti 14

到目前为止,最简单的解决方法是利用linkTo帮助程序内置的支持来在渲染链接时设置活动类.除了源代码之外,还没有记录AFAIK:

实施:https://github.com/emberjs/ember.js/blob/master/packages/ember-routing/lib/helpers/link_to.js#L46

例如:https://github.com/emberjs/ember.js/blob/master/packages/ember/tests/helpers/link_to_test.js#L120

要利用此功能,只需根据链接上的活动类而不是li元素将css调整为样式.如果你真的需要设计风格,li你可以创建一个自定义视图和帮助,扩展Ember.LinkView和使用li但更改css将更容易.

---更新----

既然我们都喜欢twitter bootstrap ,那么改变css可能不是一个很好的选择.在这种情况下,以下将做到这一点:

App.ApplicationView = Ember.View.extend({
  currentPathDidChange: function() {
    Ember.run.next( this, function() {
      this.$("ul.nav li:has(>a.active)").addClass('active');
      this.$("ul.nav li:not(:has(>a.active))").removeClass('active');
    });
  }.observes('controller.currentPath')
});
Run Code Online (Sandbox Code Playgroud)

使用ember linkTo helper和bootstrap药丸的工作示例:http://jsbin.com/ekobod/5/edit (需要ember-1.0.0-pre.4)

  • 此函数`currentPathDidChange`仅在路径深度发生变化时运行.不是在同一级别发生变化时:从`/ pages/1`到`/ pages/2` (2认同)

col*_*mba 5

活动路径的路径在ApplicationControllervia中自动更新,currentPath所以我在我的App中做了类似的事情...在这样的ApplicationController附加属性中:

isProductsActive: function(){
  if ( this.get('currentPath') === 'products' ) return 'active';
  else return '';
}.property('currentPath')
Run Code Online (Sandbox Code Playgroud)

在我的ApplicationView模板中:

<li {{bindAttr class="isProductsActive"}}>
  {{#linkTo "products"}}Products{{/linkTo}}
</li>
Run Code Online (Sandbox Code Playgroud)


ale*_*ler 5

我做了一个ember-cli插件来处理这个问题:

https://github.com/alexspeller/ember-cli-active-link-wrapper