Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This problem comes up all the time in Ember. The way I solve it is to keep track of which post is "open" on the controller and then have each item's view be responsible for its own state based on that data. That way you don't have to manually reset every post's state each time you toggle one.</p> <p>The canonical source of truth is the controller.</p> <pre><code>App.IndexController = Ember.ArrayController.extend({ content: null, selectedPost: null // null means no post selected }); </code></pre> <p>We wire this information to the components through the template.</p> <pre><code>&lt;script type="text/x-handlebars" data-template-name="index"&gt; {{#each post in controller}} {{post-summary post=post selectedPost=selectedPost}} {{/each}} &lt;/script&gt; &lt;script type="text/x-handlebars" id="components/post-summary"&gt; &lt;h3 {{action "toggleBody"}}&gt;{{post.title}}&lt;/h3&gt; {{#if isShowingBody}} &lt;p&gt;{{{post.body}}}&lt;/p&gt; {{/if}} &lt;/script&gt; </code></pre> <p>Now the body visibility for a given post can be computed by a property.</p> <pre><code>App.PostSummaryComponent = Ember.Component.extend({ post: null, selectedPost: null, isShowingBody: function() { return this.get('selectedPost') === this.get('post'); }.property('selectedPost', 'post'), toggleBody: function() { this.set('selectedPost', this.get('isShowingBody') ? null : this.get('post')); } }); </code></pre> <p><a href="http://jsfiddle.net/ahmacleod/K5b4v/" rel="nofollow">Here's the jsfiddle</a>.</p> <p>One could argue that this isn't an ideal object-oriented solution, but it has drastically improved the structure and maintainability of my Ember apps. You can implement a wide variety of complex list behaviours by having each element responsible for its own state based on a common source of truth.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload