Search code examples
javascriptember.jsconventions

Implementing an accordian-type view in Ember.js


In a toy application, I have a 'posts' template that shows all of the post titles. When you click each title, instead of heading to a 'show' view I want to expand down the rest of the contents of that post, directly inline.

I've considered having the postRoute reuse the postsRoute and set a flag that would then be checked against in the handlebars template to splat out the rest of the post content.

What would be a preferred 'Ember-ish' approach that would let a resource's singular view be rendered inline with its index view in the correct location?


Solution

  • I would suggest to define an itemController on PostsController which can take actions for individual post objects. Then, in your template define the action (e.g. toggleBody) that toggles a property on the itemController. You can use this property to show or to hide the body of each post:

    App.PostsController = Ember.ArrayController.extend
      itemController: 'post'
    
    App.PostController = Ember.ObjectController.extend
      showBody: no
      actions:
        toggleBody: ->
          @toggleProperty('showBody')
          return false
    
    <script type="text/x-handlebars" data-template-name="posts">
    <ul>
      {{#each}}
        <li>{{title}} <span {{action toggleBody}} class='label'>Toggle</span>
        {{#if showBody}}        
          <div>{{body}}</div>
        {{/if}}
        </li>
      {{/each}}
    </ul>
    </script>
    

    See also this jsFiddle for a working demo.