SO: Connected components

by fangyang

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0-rc.4/handlebars.js"></script>
<script src="http://builds.emberjs.com/ember-1.0.0-rc.6.1.prod.js"></script>
<script type="text/x-handlebars" data-template-name="index">
    {{#each post in controller}}
        {{post-summary post=post selectedPost=selectedPost}}
    {{/each}}
</script>
  
<script type="text/x-handlebars" id="components/post-summary">
    <h3 {{action "toggleBody"}}>{{post.title}}</h3>
    {{#if isShowingBody}}
        <p>{{{post.body}}}</p>
    {{/if}}
</script>

JavaScript

//http://stackoverflow.com/questions/18035560/ember-js-notify-other-components-on-one-component-action

App = Ember.Application.create();

posts = [{
    title: "Rails is omakase",
    body: "There are lots of Ă  la carte software environments in this world."
}, {
    title: "Broken Promises",
    body: "James Coglan wrote a lengthy article about Promises in node.js."
}];

App.IndexController = Ember.ArrayController.extend({
    selectedPost: null 
});

App.IndexRoute = Ember.Route.extend({
    model: function () {
        return posts;
    }
});

App.PostSummaryComponent = Ember.Component.extend({
    post: null,
    selectedPost: null,

    isShowingBody: function() {
        return this.get('selectedPost') === this.get('post');
    }.property('selectedPost'),

    toggleBody: function() {
        this.set('selectedPost', 
                 this.get('isShowingBody') ? null : this.get('post'));
    }    
});