Backbone Js中的嵌套视图,帖子和;评论关系

时间:2013-05-21 19:53:46

标签: backbone.js backbone-views

对象数组

从服务器

接收数据
var Updates = [
{"post_id":"1","post_desc":"This is my first  post",
     "comments":[{"id":1,"comment":"some comments","like":7},
                 {"id":9,"comment":"some   comments","like":3}
                ]
},
{"post_id":"2","post_desc":"This is my second  post",
     "comments":[{"id":5,"comment":"some comments","like":5}]
}]

型号:

var Update = Backbone.Model.extend({
   defaults:{
    photo: "default.png"
   }
 });

收集:

var latestUpdates = Backbone.Collection.extend({
    model: Update
});

单一视图:

var UpdateView = Backbone.View.extend({
tagName: "div",
className: "post-container",
template: $("#postTemplate").html(),

render: function () {
    var tmpl = _.template(this.template);

    this.$el.html(tmpl(this.model.toJSON()));
    return this;
}
});

主视图:

var UpdatesView = Backbone.View.extend({

el: $("#postContainer"),

initialize: function () {
    this.collection = new latestUpdates(Updates);
    this.render();
},
render: function () {
    var that = this;
    _.each(this.collection.models, function (item) {
        that.renderUpdates(item);
    }, this);
},
renderUpdates: function (item) {
    var updateView = new UpdateView({
        model: item
    });
    this.$el.append(updateView.render().el);
}

});

//create app instance
var wallUpdates = new UpdatesView();

如何在每个帖子下呈现评论部分? 试图实现类似于facebook post-comment system的布局

1 个答案:

答案 0 :(得分:0)

我使用CommentListView拥有的UpdateViewtagName: "ul", className: "post-comments"

然后CommentView拥有CommentListView。 CommentView的渲染不应该向DOM附加任何内容,而是返回其$el

CommentListView会告诉每个CommentView要呈现,并将$el的每个CommentListView附加到$el的{​​{1}}。< / p>

对于容器,我会使用:

<div class="post-container" data-post-id="<%= YourPostId %>">
    <div class="post-body">
        <!--Your post can go in here-->
    </div>
    <ul class="post-comments">
        <!--Append your comments in here-->
    </ul>
</div>
相关问题