Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind to the active class of a link using the new Ember router?

Tags:

I'm using Twitter Bootstrap for navigation in my Ember.js app. Bootstrap uses an active class on the li tag that wraps navigation links, rather than setting the active class on the link itself.

Ember.js's new linkTo helper will set an active class on the link but (as far as I can see) doesn't offer any to hook on to that property.

Right now, I'm using this ugly approach:

{{#linkTo "inbox" tagName="li"}}   <a {{bindAttr href="view.href"}}>Inbox</a> {{/linkTo}} 

This will output:

<li class="active" href="/inbox"><a href="/inbox">Inbox</a></li> 

Which is what I want, but is not valid HTML.

I also tried binding to the generated LinkView's active property from the parent view, but if you do that, the parent view will be rendered twice before it is inserted which triggers an error.

Apart from manually recreating the logic used internally by the linkTo helper to assign the active class to the link, is there a better way to achieve this effect?

like image 550
Nick Ragaz Avatar asked Jan 14 '13 22:01

Nick Ragaz


Video Answer


2 Answers

We definitely need a more public, permanent solution, but something like this should work for now.

The template:

<ul> {{#view App.NavView}}   {{#linkTo "about"}}About{{/linkTo}} {{/view}}  {{#view App.NavView}}   {{#linkTo "contacts"}}Contacts{{/linkTo}} {{/view}} </ul> 

The view definition:

App.NavView = Ember.View.extend({   tagName: 'li',   classNameBindings: ['active'],    active: function() {     return this.get('childViews.firstObject.active');   }.property() }); 

This relies on a couple of constraints:

  • The nav view contains a single, static child view
  • You are able to use a view for your <li>s. There's a lot of detail in the docs about how to customize a view's element from its JavaScript definition or from Handlebars.

I have supplied a live JSBin of this working.

like image 155
Yehuda Katz Avatar answered Oct 18 '22 18:10

Yehuda Katz


Well I took what @alexspeller great idea and converted it to ember-cli:

app/components/link-li.js

export default Em.Component.extend({     tagName: 'li',     classNameBindings: ['active'],     active: function() {         return this.get('childViews').anyBy('active');     }.property('[email protected]') }); 

In my navbar I have:

{{#link-li}}     {{#link-to "squares.index"}}Squares{{/link-to}} {{/link-li}} {{#link-li}}     {{#link-to "games.index"}}Games{{/link-to}} {{/link-li}} {{#link-li}}     {{#link-to "about"}}About{{/link-to}} {{/link-li}} 
like image 45
Adam Klein Avatar answered Oct 18 '22 19:10

Adam Klein