如何在emberjs中构建嵌套视图

时间:2013-04-14 14:01:01

标签: ember.js

我正在努力学习余烬并理解所有概念。我现在被困了几天。

我尝试创建一个包含多个“子视图”的视图(在ember中是否有它的名称?)。例如:

+-----------------------------------------------+------------------+
| Post title                                    | new tag: ______  |
+-----------------------------------------------+                  |
| Post text                                     | * tag 1          |
|                                               | * tag 2          |
|                                               |                  |
+-----------------------------------------------+------------------+
| New comment: _____________ submit             | related posts    |
|                                               |                  |
| * comment 1 text                              | * post 1         |
| * comment 2 text                              | * post 2         |
| * comment 3 text                              |                  |
| * comment 4 text                              |                  |
| * comment 5 text                              |                  |
|                                               |                  |
+-----------------------------------------------+------------------+

我的想法是让PostController有自己的路线来显示所选帖子的详细信息。添加注释和小部件的嵌套元素(使用{{#each}})很容易。这意味着我需要处理我的PostController中嵌套元素的所有操作和其他所有操作,这些元素闻起来很糟糕并且变得混乱。

不应该是separate controller中的每一个(评论,标签和相关)吗?在这种情况下,我可以保持我的PostController清洁并处理其自己的控制器中的所有嵌套操作。这是正确的方式还是有更好的方法来实现它?

如果是,我该如何实现这些嵌套视图。我在ember中阅读了很多关于嵌套视图的主题,但我无法弄清楚它的概念。我会说,我不需要标记和注释的路由,因为它绑定到PostController并且它们从未在没有帖子的情况下使用,但我不确定。

在阅读this post之后,我尝试使用渲染但我不理解在这种情况下使用控制器和视图的概念。

是否有一个好的(更新的)指南,我错过了或者有人可以解释一下这是如何工作或指导我朝正确的方向发展的?

1 个答案:

答案 0 :(得分:2)

您可以按Em.View.create
创建单独的视图 然后使用post插入{{view}}模板进行评论&标签

模板:

<script type='text/x-handlebars' data-template-name='post'>
<div class='post'>
  <h1>{{title}}</h1>
  <div class='content'>{{{content}}}</div>
  <div class='tags'>{{view App.TagView}}</div>
  <div class='comments'>{{view App.CommentView}}</div>
  <div class='relatedPosts'>{{view App.RelatedPostView}}</div>
</div>
</script>

<script type='text/x-handlebars' data-template-name='comment'>
{{#each view.comments}}
  <!--some HTML codes for comments-->
{{/each}}
</script>

脚本:

App.CommentView = Em.View.create({
  templateName:'comment',
  comments:[],
  didInsertElement: function(){
    // Handler related to this view has to implement here
    // as there are delays for inserting elements
  }
});

App.PostController = Em.ArrayController.extend({
  getContent: function(){
    //some codes for loading content

    //You can implement all methods in single controller
    this.addComments(data.comments);

    //Or call other methods after loaded the content
    App.commentController.setup(data.comments);
  },
  addComments: function(data){
    App.CommentView.set('comments',data);
  }
});
相关问题