Assigning 'active' class to selected list item in EmberJS

后端 未结 12 2084
星月不相逢
星月不相逢 2020-12-08 00:34

I have a list and I\'d like to set one item as class=\"active\" automatically. Given the following bootstrap code:

12条回答
  •  旧巷少年郎
    2020-12-08 01:13

    By far the cleanest way to solve this is by taking advantage of the linkTo helper's built-in support for setting the active class when rendering links. AFAIK this is not yet documented other than in the source code:

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

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

    To take advantage of this feature just adjust your css to style based on having an active class on the link instead of the li element. If you really need to style the li you can create a custom view and helper that extends Ember.LinkView and uses an li but changing css will be far easier.

    --- UPDATE ----

    Since we all love twitter bootstrap just changing the css is perhaps not such a great option. In that case, the following will do the trick:

    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')
    });
    

    Working example using ember linkTo helper with bootstrap pills: http://jsbin.com/ekobod/5/edit (requires ember-1.0.0-pre.4)

提交回复
热议问题