Make navigation item active if route does not match

I noticed that using EmberJS, if the route you are on matches the link with the same path on your page, it automatically accepts the "active" class.

I am currently creating a navigation bar that uses this, but my concern is that not all of my routes correspond to my navigation bar.

For example, when I am on the /messages route, I would like to make the /services element active. Or, when I'm on the /forums/history route, I would like to make the /forums/archives element active. Although this route is not in navigation, I want to highlight the element that is associated with it.

My navigation is created from a json object that looks like this:

 [ { "label": "Forums", "link": "forums", "children": [ { "label": "Latest" "link": "forums.latest" } { "label": "Archives" "link": "forums.archives" } ] } ] 

I had a few ideas that I don’t like, so I come here to get your advice. Here are my ideas:

  • Define a property in the view to determine which item should be active in navigation:

views / forum / history.js:

 Ember.View.extend({ navigationActiveItem: 'forums.archives' }); 
  • Define in my json object a list of links that will highlight the element

Json file:

 [ { "label": "Forums", "link": "forums", "children": [ { "label": "Archives" "link": "forums.archives", "makeActive": ["forums.history", "forums.records"] //If you are on one of those route, it will active forums.archives } ] } ] 

router.js:

 Router.map(function () { this.route('forums', function () { this.route('latest'); this.route('archives'); this.route('history'); }); }); 

Do you have any better suggestion to do this? Thanks

+5
source share
2 answers

Use the current-when parameter {{# link-to}}. This will allow you to identify alternative routes that cause the link to be active.

Since ember 1.8, current-when can take a route string limited to spaces. For an implementation that works in version 1.7, check Is there a way to pass the currentWhen array to EmberJS?

+4
source

The way I do this is to set properties in my application controller.

(It is assumed that your navigation bar template is in application.handlebars )

For example, if you want the Forums tab to be active on any forums track, you could create a property called something like isForums that looks like this:

 isForums: function(){ return this.get('currentPath').split('.')[0] === 'forums'; }.property('currentPath') 

You can then access this from application.handlebars as follows:

 <li {{bind-attr class="isForums:active"}}> {{#link-to "forums"}}Forums{{/link-to}} </li> 

This adds the active class to <li> if isForums is true.

+1
source

Source: https://habr.com/ru/post/1204451/


All Articles