Zofren
Zofren

Reputation: 1190

Expand/Collapse sidebar with the same button with Ember

I'm trying to implement simple behavior to learn Ember and I'm hitting a wall with the sidebar implementation.

This is an expandable/collapsable sidebar with icons. When icon is clicked, it is highlighted and the corresponding content is displayed on the expanded sidebar pane. When clicking again on the same icon, the sidebar collapse and the application returns to the corresponding index route.

I got quite close to this defined behavior but I always miss a little thing.

<div id="sidebar" {{bind-attr class='selectedTab::collapsed'}}>
<div id="sidebar-items">
    {{#each}}
        {{#link-to target tagName="li"}}
            <a {{bind-attr href=view.href}}>{{fa-icon icon}}</a>
        {{/link-to}}
    {{/each}}
</div>
<div id="sidebar-pane">
    {{outlet}}
</div>
</div>

In this implementation, I can not collapse the sidebar because if I click again on the same icon, Ember does not attempt the route again so I can't reach the code where I'm testing the requested route against the current one, and where I transition to index route if equals. I tried with the willTransition hook with no success.

<div id="sidebar" {{bind-attr class='selectedTab::collapsed'}}>
<div id="sidebar-items">
    {{#each}}
        <li>
            <a {{action 'selectTab' target}}>
                {{fa-icon icon}}
            </a>
        </li>
    {{/each}}
</div>
<div id="sidebar-pane">
    {{outlet}}
</div>
</div>

This is the closer I got to what I need. In this one, I can make all the process in the selectTab function and redirect to the correct route, or index if I detect this is the same route as the current one. The sidebar expand and collapse, the content pane is updated accordingly with the route. But, I didn't find how to bind the active class on the selected <li> AND remove the active class on all siblings.

Any idea ?

Upvotes: 0

Views: 743

Answers (1)

Sam Selikoff
Sam Selikoff

Reputation: 12694

It's hard to understand what's going on with your {{#each}}. Is that each model, controller, something else?

In any case, whatever this is (lets say a Tab model), you just want to know if a Tab isSelected or not. Then, you can bind the class to isSelected while you're iterating over each.

If the controller is handling selectTab, it should just be able to do something like this:

selectTab: function(tab) {
  this.get('tabs').setEach('isSelected', false);
  tab.set('isSelected', true);
}

Then you can do <li {{bind-attr class='isSelected:active'}}>.

Upvotes: 0

Related Questions