这个问题在 Ember 中一直出现。我解决它的方法是跟踪控制器上“打开”的帖子,然后让每个项目的视图根据该数据负责自己的状态。这样,您不必在每次切换时手动重置每个帖子的状态。
规范的事实来源是控制器。
App.IndexController = Ember.ArrayController.extend({
content: null,
selectedPost: null // null means no post selected
});
我们通过模板将此信息连接到组件。
<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>
现在可以通过属性计算给定帖子的正文可见性。
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'));
}
});
这是 jsfiddle。
有人可能会说这不是一个理想的面向对象的解决方案,但它极大地改善了我的 Ember 应用程序的结构和可维护性。您可以通过让每个元素基于共同的事实来源负责自己的状态来实现各种复杂的列表行为。