Search code examples
javascriptember.jsember-router

Ember losing active trail


Hi I have the following Routes in ember:

App.Router.map(function(){

    this.resource('meat', function() {
        this.resource('poultry', function() {
            this.route('chicken');
            this.route('duck');
        });
    });
});

My templates look like this:

<script type='text/x-handlebars' id='meat'>       
     <div>{{outlet}}</div>
</script>


<script type='text/x-handlebars' id='poultry'>
       Poultry
       <br/><br/>
          {{#link-to 'poultry.chicken'}}Chicken{{/link-to}}
          {{#link-to 'poultry.duck'}}Duck{{/link-to}}

      <br/><br/>
      <div>
         {{outlet}}
      </div>
</script>

<script type="text/x-handlebars" id="poultry/chicken">
    <h4>Chicken</h4>
</script>

<script type="text/x-handlebars" id="poultry/duck">
    <h4>Duck</h4>
</script>

The problem is, when I click on the 'Duck' link, I lose my active trail to 'Poultry'.

I can't figure it out, the path is correct, but the active classes are gone.

Here is a jsbin: http://emberjs.jsbin.com/yularepare/2/

Thanks!


Solution

  • The code in your comment is a little different than the JSBin. You didn't include the application template. Here it is:

    <script type='text/x-handlebars' data-template-name='application'>
      {{#link-to 'poultry.chicken' }}Poultry{{/link-to}}  
    
      <br/><br/>
      <div>
        {{outlet}}
      </div>
    </script>
    

    You're losing the active class because you're linking straight to 'poultry.chicken', not 'poultry'. It isn't a parent route, but a sibling route. If you want to keep the active class, change you link-to to:

    {{#link-to 'poultry'}}Poultry{{/link-to}}

    and it should work fine. Working JSBin: http://jsbin.com/fefucalaqi/1/edit

    EDIT: comment asked how to handle redirect to first result. Adding here.

    App.PoultryIndexRoute = Ember.Route.extend({
      redirect: function() {
        // write some code to get to your first result here.
        this.transitionTo('poultry.chicken');
      }
    });
    

    Now you'll get both: active class on all poultry routes and you'll show the first one if none were selected.