在EmberJS中,我的事件会触发所有子视图,而不仅仅是目标子视图

时间:2012-05-13 23:58:51

标签: ember.js

我正在学习EmberJS并建立一个允许1级子评论的评论部分。我有一个列出所有评论的Ember View,当你点击特定评论的“回复”时,它应该显示一个textarea输入,供用户写一个子评论。

在我的EmberJS代码中,当您单击“回复”时,它会显示所有注释的textarea输入,而不仅仅是特定注释。任何建议将不胜感激:)

// View
App.commentsView = Em.View.create({
templateName: 'commentsTmpl',
showReply: false,

reply: function(e) {
    e.view.set('showReply', true);
    e.preventDefault();
}
}); 

App.replyCommentsView = Em.View.extend({
showReplyBinding: 'App.commentsView.showReply'
});
// Template
<script data-template-name="commentsTmpl" type="text/x-handlebars">
</h2>comment</h2>
{{#each App.commentsController}}
<div class="comment-group clearfix">
  <div class="comment">
    <img class="comment-pic" {{bindAttr src="userPic"}} alt="user pic"> 
    <div class="comment-content">
        <a href="#" class="comment-username">{{userName}}</a> 
        <span class="comment-body">{{text}}</span>
        <div class="comment-actions clearfix">
          <a href="#" {{action "reply"}}>Reply</a>
        </div>
    </div>
  </div>
{{#view App.replyCommentsView}}
  {{#if showReply}}
  <div class="comment-reply">
    <h2>sub-comment</h2>
    <textarea class="txt-comment-reply" rows="2" cols="65"></textarea>
  </div>
  {{/if}}
{{/view}}
</div>
  {{/each}}
</script>

1 个答案:

答案 0 :(得分:1)

目前,您将showReply绑定到App.commentsView,这是整个容器。为了方便激活单个评论,我建议您查看CollectionView,这样您的每条评论都会有自己的视图,您可以在单个评论的视图上切换showReply

这样的事情:(对不起,我还没有测试过)

App.commentsView = Em.View.create({
  templateName: 'commentsTmpl'
}); 

App.CommentView = Em.View.extend({
  classNames: "comment-group clearfix".w(),
  showReply: false,

  reply: function(e) {
    e.preventDefault()
    this.set("showReply", true)
  }
})
// Template
<script data-template-name="commentsTmpl" type="text/x-handlebars">
  </h2>comment</h2>
  {{#collection contentBinding="App.commentsController" itemViewClass="App.CommentView"}}
      <div class="comment">
        <img class="comment-pic" {{bindAttr src="content.userPic"}} alt="user pic"> 
        <div class="comment-content">
          <a href="#" class="comment-username">{{content.userName}}</a> 
          <span class="comment-body">{{content.text}}</span>
          <div class="comment-actions clearfix">
            <a href="#" {{action "reply"}}>Reply</a>
          </div>
        </div>
      </div>
      {{#if showReply}}
      <div class="comment-reply">
        <h2>sub-comment</h2>
        <textarea class="txt-comment-reply" rows="2" cols="65"></textarea>
      </div>
      {{/if}}
  {{/each}}
</script>