【问题标题】:Backbone: dynamic views hierarchy with templatesBackbone:带有模板的动态视图层次结构
【发布时间】:2012-12-29 14:11:25
【问题描述】:

我有三个不同的视图模板:“发布”、“评论”、“添加新评论”。主要模板是“post”。我需要了解如何将“cmets”和“添加新评论”模板放入“post”模板中的 div 中。或任何其他方法来制作这个结构:

- 邮政 - 厘米 - 添加新的帖子表单 - 邮政 ...

类似于脸书墙

Backbone 的 Javascript:

// Post View
var PostView = Backbone.View.extend({
    template: $("#post").html(),
    ...
    render: function () {
        var tmpl = _.template(this.template);
        var thisPost = this.model.toJSON();
        this.$el.html(tmpl(thisPost));
    }
});
var postView = new PostView();
postView.render();

// Comments List
var CommentsListView = Backbone.View.extend({
    el: '#comments', // how to place it to #comments div in "post" template? This line doesn't work
    ...
    addNewCommentForm: function (post_id) {
        var tmpl = _.template($("#addCommentTemplate").html());
        this.$('#addNewComment').append(tmpl()); // How to place it to #addNewComment div in "post" template? This line doesn't work
    }
});

HTML:

<script id="post" type="text/template">
    <%= text %>
    <div id='comments'>...</div>
    <div id='addNewComment'>...</div>
</script>

【问题讨论】:

    标签: templates backbone.js views


    【解决方案1】:

    您的代码有很多问题。首先是您实际上并没有将PostView.el 放入DOM。通过PostView.render(),您正在填充PostView.$el,然后是PostView.el,但实际上并没有将其放入页面(DOM)中。此外,通过在CommentsListView 上设置el,您实际上并没有在那里做任何事情。如果您想将el 设置为现有元素,则可以执行以下操作:el: $('#comments')。或者,如果您想动态渲染 CommentsListView 并将其注入 DOM,那么您可能只想通过像这样定义 id 属性使元素具有“cmets”的 id:id: 'comments'。这些只是代码中最明显的两个问题。我在这里运行了一个半工作示例:http://codepen.io/jayd3e/pen/hAEDv

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      • 2014-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多