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

前端 未结 9 1601
天命终不由人
天命终不由人 2020-12-08 01:17

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 th

相关标签:
9条回答
  • 2020-12-08 01:49

    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.

    0 讨论(0)
  • 2020-12-08 01:49

    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('childViews.@each.active')
    });
    

    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}}
    
    0 讨论(0)
  • 2020-12-08 01:54

    Building on katz' answer, you can have the active property be recomputed when the nav element's parentView is clicked.

    App.NavView = Em.View.extend({
    
        tagName: 'li',
        classNameBindings: 'active'.w(),
    
        didInsertElement: function () {
            this._super();
            var _this = this;
            this.get('parentView').on('click', function () {
                _this.notifyPropertyChange('active');
            });
        },
    
        active: function () {
            return this.get('childViews.firstObject.active');
        }.property()
    });
    
    0 讨论(0)
提交回复
热议问题